How to upload pdf file into firebase by using iOS - ios

Can I upload pdf files into firebase using Swift?.
If it is possible please share me the code.
I'm using the below code
let proofRef = filesstorgRef.child(timestamp)
let uploadTask = proofRef.putData(data, metadata: nil, completion: { (metadata, error) in
if error != nil {
//print("Failed to upload image:", error)
return
}
if let fileUrl = metadata?.downloadURL()?.absoluteString {
completion(fileUrl)
}
})
uploadTask.observe(.progress) { (snapshot) in
if (snapshot.progress?.completedUnitCount) != nil {
print("ImageUploadingPerCent=== \(String(describing: snapshot.progress?.completedUnitCount))")
}
}
uploadTask.observe(.success) { (snapshot) in
print("ImageUploading Success")
}
uploadTask.observe(.failure) { (snapshot) in
LoadingView.sharedInstance.visible(visible: false)
print("ImageUploading failure")
}
thanks in advance

// Get the default app firebse storage reference
let FIRStorage = Storage.storage()
// reference of the storage
let storageRef = FIRStorage.reference()
// You have to get the file URL from disk or anywhere
let filePath = Bundle.main.path(forResource: "mypdf", ofType: "pdf")
let filePathURL = URL(fileURLWithPath: filePath!)
// Create a reference/Path on firebase database, where you want to upload your file
let fileRef = storageRef.child("firebase path with filename")
// from this you cant upload the file on fileRef path
let uploadTask = fileRef.putFile(from: filePathURL, metadata: nil) { metadata, error in
guard let metadata = metadata else {
// error!
return
}
let metadataSize = metadata.size
// get the download url of this file
fileRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// error!
return
}
}
}
Try this code.

Related

ImageView to Firebase Storage in Swift

I am trying to upload an image from ImageView to Firebase storage but it won't work.
I have listed my code below: My image view is called ProfileImage
let storageRef = Storage.storage().reference().child("myImage.png")
if let uploadData = self.ProfileImage.image!.pngData() {
storageRef.putFile(from: uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("error")
completion(nil)
} else {
// your uploaded photo url.
}
}
}
It comes up with the error "Cannot convert value of type 'Data' to expected argument type 'URL'
You are trying to upload Data, not a file. Replace
putFile
With
putData
And it should work fine
Try this code :-
let storageRef = Storage.storage().reference().child("myImage.png")
if let uploadData = UIImagePNGRepresentation(self.profileImage.image!) {
storageRef.put(uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("\(error.localizeDescription)")
} else {
// your uploaded photo url.
}
}
let refDatabase = Database.database().reference()
var refstorage = Storage.storage().reference()
let data = image.jpegData(compressionQuality: 1.0) //
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
let postkey = refDatabase.child("Post").childByAutoId().key
print(postkey)
let imagename = "PostImage/\(postkey).png"
refstorage = refstorage.child(imagename)
let timestamp = Date().timeIntervalSince1970 // you can use this to track time when it was uploaded.
self.refstorage?.putData(data!, metadata: metadata, completion: { (meta, error) in
if error == nil{
if let imageData = meta?.downloadURL()?.absoluteString{
// DO SOMETHING
} else {
print("Couldn't get the URL for image")
}
}
})
I know that this question has been answered, but there is an easier way to do this. Along with import Firebase and Firebase Storage, you will also have to add FirebaseUI to your podfile and import it.
After you have done that, you could get your image to your app much simpler.
let storage = Storage.storage()
let storageRef = storage.reference()
let placeholderImage = UIImage(named: "placeholder.jpeg")
let reference = storageRef.child("myImage.png")
ProfileImage.sd_setImage(with: reference, placeholderImage: placholderImage)
(The placeholder Image would just be a transparent image that you put in your assets folder in XCode that you could reuse multiple times in your application, for whenever you needed to get a Firebase Image on your app.)

How to get rid of the word optional before a url saved in firebase?

Currently I am saving the url of images stored in the firebase database. However I am getting the word optional before the url. As seen bellow.
"Optional(https:URL.HERE)"
The following is the code block where the saving happens:
if let imageData = UIImageJPEGRepresentation(image, 0.8) {
let metadata = storageRef //.child("poop/")
let uploadTask = metadata.putData(imageData, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
return
}
// You can also access to download URL after upload.
storageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// Uh-oh, an error occurred!
return
}
let imgURL = url
//database integration
let ref = Database.database().reference()
let usersRef = ref.child("usersPosts")
let uid = Auth.auth().currentUser?.uid
let newUserRef = usersRef.child(uid!)
//creates a child for email and password (i think we shud store password so we can tell sumone what it is inmediatly, maybe)
newUserRef.setValue(["Image": "\(imgURL)"])
}
}
// For progress
uploadTask.observe(.progress, handler: { (snapshot) in
guard let progress = snapshot.progress else {
return
}
let percentage = (Float(progress.completedUnitCount) / Float(progress.totalUnitCount))
progressBlock(Double(percentage))
})
} else {
completionBlock(nil, "Image could not be converted to Data.")
}
You are getting Optional... because imgURL is optional. And imgURL is optional because you assigned it from url which is optional.
Since you already unwrapped url in the guard statement, just use downloadURL instead of creating imgURL.
Remove:
let imgURL = url
And replace the use of imgURL with downloadURL which is the properly unwrapped version of url from the guard.
newUserRef.setValue(["Image": "\(downloadURL)"])

Swift4 : Download photo from Firebase

I want to download a photo that was previously uploaded from Firebase. I am using the following code:
fbUser = Auth.auth().currentUser
let storage = Storage.storage()
let storageRef = storage.reference(forURL: "somepath.some")
let profilePicRef = storageRef.child(fbUser.uid+"_profile_pic.jpg")
var imageFB : UIImage? = nil
profilePicRef.downloadURL(completion: { (url, error) in
if error != nil {
print(error!)
return
}
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
guard let imageData = UIImage(data: data!) else { return }
DispatchQueue.main.async {
imageFB = imageData
}
}).resume()
})
The photo is there - if I delete the photo, then I get an error that the file is missing. However, after the download, imageFB is always equal to nil, even if the photo is there.
Any suggestions on how to fix that?
Firebase includes FirebaseUI, which helps managing image downloading / caching. Following the documentation, you should be able to download and display an image in a few simple lines of code.
I suggest you take a look at documentation. The link will take you to the image downloading section with an example on how to install and use it.
Try this let us know if works.
fbUser = Auth.auth().currentUser
let storage = Storage.storage()
let storageRef = storage.reference(forURL: "somepath.some")
let profilePicRef = storageRef.child(fbUser.uid+"_profile_pic.jpg")
// give your db ref var here
let ref = Database.database().reference()
let usersRef = ref.child("users").child(uid!)
var picArray: [UIImage]()
Download:
usersRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
profilePicRef.downloadURL(completion: { (url, error) in
let data = Data(contentsOf: url!)
let image = UIImage(data: data! as Data)
picArray.append(image)
})
})

How to upload CSV file in google drive in swift 3

I am using google drive SDK for uploading CSV file. I used code given in google but error is coming
func create(){
let fileData = FileManager.default.contents(atPath: "FL_insurance_sample.csv")
let folderId: String = self.fileId!
let metadata = GTLRDrive_File.init()
metadata.name = "FL_insurance_sample"
metadata.mimeType = "application/vnd.google-apps.spreadsheet"
metadata.parents = [folderId]
let uploadParameters = GTLRUploadParameters(data: fileData! , mimeType: "text/csv")
uploadParameters.shouldUploadWithSingleRequest = true
let query = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: uploadParameters)
query.fields = "id"
self.service.executeQuery(query, completionHandler: {(ticket:GTLRServiceTicket, object:Any?, error:Error?) in
if error == nil {
// print("File ID \(files.identifier)")
}
else {
print("An error occurred: \(error)")
}
})
}
It showing nil error on uploadParameters at fileData. Can anyone help me out.
Variable fileData is nil because you've passed the wrong file path. To get correct file path use:
guard let filePath = Bundle.main.path(forResource: "FL_insurance_sample", ofType: "csv") else {
print("No such file in bundle")
// handle situation
return
}
guard let fileData = FileManager.default.contents(atPath: filePath) else {
print("Can't read file")
// handle situation
return
}
// upload fileData

Generating a download link using firebase

I'm creating an application that lets the user upload an image and then display a direct link in a text field.
Here is the code that is responsible for uploading the image to my bucket and it is triggered when the user's press the upload button.
#IBAction func upload(_ sender: Any) {
let imageContained = viewimage.image
let storage = Storage.storage()
var storageRef = storage.reference()
storageRef = storage.reference(forURL: "bucket link")
var data = NSData()
data = UIImageJPEGRepresentation(imageContained!, 0.8)! as NSData
let dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let imageName = dateFormat.string(from: NSDate() as Date)
let imagePath = "images/\(imageName).jpg"
let mountainsRef = storageRef.child(imagePath)
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
mountainsRef.putData(data as Data, metadata: metadata)
How would I generate a direct link for the user?
Use this below function
func uploadProfilePic(){
var data = NSData()
data = UIImageJPEGRepresentation(ivProfile.image!, 0.8)! as NSData
// set upload path
let filePath = "\(userid)" // path where you wanted to store img in storage
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
self.storageRef = FIRStorage.storage().reference()
self.storageRef.child(filePath).put(data as Data, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
}else{
//store downloadURL
let downloadURL = metaData!.downloadURL()!.absoluteString
}
}
}
Upload function with completion handler.
func uploadMedia(completion: #escaping (_ url: String?) -> Void) {
let storageRef = FIRStorage.storage().reference().child("myImage.png")
if let uploadData = UIImagePNGRepresentation(self.myImageView.image!) {
storageRef.put(uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("error")
completion(nil)
} else {
completion((metadata?.downloadURL()?.absoluteString)!))
// your uploaded photo url.
}
}
}
Hope it helps

Resources