Firebase storage how to get uploading images progress in Swift - ios

I'm trying to get progress of uploading images and I saw the explanation link below. However what I want to do is uploading multiple images.
link here
I implemented like this to upload images.
for image in imagesArray {
let postRef = ref.child("post").child(uid)("images")
let autoId = postRef.childByAutoId().key
let childStorageRef = storageRef.child("images").child(autoId)
if let uploadData = UIImagePNGRepresentation(image) {
childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
print("error")
return
} else {
if let imageUrl = metadata?.downloadURL()?.absoluteString {
let val = [autoId: imageUrl]
postRef.updateChildValues(val)
}
}
})
}
}
I tried call observe(.progress)
But there is only childStorageRef.observe(<#T##keyPath: KeyPath<StorageReference, Value>##KeyPath<StorageReference, Value>#>, options: <#T##NSKeyValueObservingOptions#>, changeHandler: <#T##(StorageReference, NSKeyValueObservedChange<Value>) -> Void#>)
So, I don't know how to get progress like link.
How can I achieve this? Thank you in advance!

Swift- 5 Easy Way
let storageRef = FIRStorage.reference().child("folderName/file.jpg");
let localFile: NSURL = // get a file;
// Upload the file to the path "folderName/file.jpg"
let uploadTask = storageRef.putFile(localFile, metadata: nil)
uploadTask.observe(.progress) { snapshot in
print(snapshot.progress) // NSProgress object
}

1. First, create a variable of your query:
(Just add "let uploadTask = " before the query)
Example: let uploadTask = childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in...
2. Then you can call this observers:
(Observe progress)
uploadTask.observe(.progress, handler: { (snapshot) in
or
(Observe when success)
uploadTask.observe(.success, handler: { (snapshot) in
or
(Observe if fail)
uploadTask.observe(.failure, handler: { (snapshot) in

Related

Value of type 'StorageMetadata' has no member 'downloadURL' in swift and firebase

I'm currently watching a youtube video telling me how to make a social media app. But when I was writing the code, I encountered an error in this function. This is a very annoying error, so if you can, please help me
func setupUser(userUid: String) {
if let imageData = self.userImgView.image!.jpegData(compressionQuality: 0.2) {
let imgUid = NSUUID().uuidString
let metaData = StorageMetadata()
Storage.storage().reference().child(imgUid).putData(imageData, metadata: metaData) { (metadata, error) in
let downloadURL = metadata?.downloadURL()?.absoluteString
let userData = [
"username": self.usernameField.text!,
"userImg": downloadURL!
] as [String : Any]
Database.database().reference().child("users").child(userUid).setValue(userData)
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
}
The error happened in this code...
let downloadURL = metadata?.downloadURL()?.absoluteString
There are other questions on Stackoverflow like this one, but I tried all of them but got an error. Can you please help me. Can you just edit my code a little bit to fix it? Please don't lead me straight to the documentation. I've tried that but it didn't work
You can use this function for uploading content in firebase storage
typealias blockCompletedWith = (Bool, String) -> Void
func uploadToFirebaseStorage(data: Data, path: String, blockCompletedWith: #escaping blockCompletedWith) {
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg" //Modify as per your need
let store = Storage.storage()
let storeRef = store.reference().child(path)
let _ = storeRef.putData(data, metadata: metadata) { (metadata, error) in
guard let _ = metadata else {
print("error occured: \(error.debugDescription)")
blockCompletedWith(false, "")
return
}
storeRef.downloadURL(completion: { (url, error) in
if let urlText = url?.absoluteString {
blockCompletedWith(true, urlText)
}
else {
blockCompletedWith(false, "")
}
})
}
}
After getting the URL from this function you can do your further processing on data as per your need.
Please let me know if you have any questions.
Happy to help!
The correct thing to downgrade the podfile. In you podfile, type
pod 'Firebase/Storage', '4.4.0'
Then it will work. You don't have to downgrade other podfiles.

videos uploaded to firebase are 0 seconds long?

I have an app where you can upload videos to firebase. The problem I have recently encountered is that all videos uploaded to firebase are 0 sec long (This is when in the DB, before, as in in the app, they are of correct length), which is of course wrong.
Some things I've tried:
I check how I upload which i also included bellow and it seems correct.
thumbnail is of type UIImage
The video right before I send it (in the preview I have in-app) the video looks perfect.
Another thing I noticed is that a thumbnail I upload with the video which is an image is being uploaded as a video.
} else if let vidData = media.videoURL {
print("VIDEO")
let autoIDSto = "media\(media.numMedia).mov"
print(autoIDSto)
let autoID = "media\(media.numMedia)"
let storageRef = Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post:\(postID)").child(autoIDSto)
let postRef = childRef.child("Media")
let uploadData = media.videoURL
let uploadTask = storageRef.putFile(from: vidData, metadata: nil) { (metadata, error) in
print("\(vidData) : Video data")
guard let metadata = metadata else { return }
if let error = error {
print(error)
}
storageRef.downloadURL(completion: { (url, error) in
//a bunch of code to add to DB
if let thumbnailImageData = media.thumbnailImage!.jpegData(compressionQuality: 1.0) {
storageRef.putData(thumbnailImageData, metadata: nil) { (metadata, error) in
storageRef.downloadURL(completion: { (url, error) in
if let thumbnail = url {
mediaRef.updateChildValues(["thumbnail" : "\(thumbnail)"])
Whats wrong and how can I fix it?
You use the same path ( 1 with mov extension )
let storageRef = Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post:\(postID)").child(autoIDSto)
to store the video/image thumbnail here
let uploadTask = storageRef.putFile(from: vidData, metadata: nil) { (metadata, error) in
and
storageRef.putData(thumbnailImageData, metadata: nil) { (metadata, error) in
There should be 2 different paths 1 with mov extension and another with jpg extension that you finally store the reference of both in 1 record in your database table

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 upload pdf file into firebase by using 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.

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