Daibaku
Daibaku

Reputation: 12566

Firebase storage how to get uploading images progress in Swift

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!

Upvotes: 1

Views: 1936

Answers (2)

Shakeel Ahmed
Shakeel Ahmed

Reputation: 6023

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
}

Upvotes: 2

Caue Borella
Caue Borella

Reputation: 53

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

Upvotes: 1

Related Questions