Bright
Bright

Reputation: 5741

Firebase Storage iOS put file completion handler called before upload finishes

I was trying to upload videos to Firebase Storage, and when the upload finishes, I store the location of this video file to an object in the database, my code is as below:

Storage.storage().reference(withPath: mediaURL!).putFile(from: localCacheURL, metadata: nil, completion: { (metadata, error) in
    if error != nil {
        print("❗️failed to upload video")
    } else {
        print("a video is uploaded")
        json = ["text": "", "image": "", "video": mediaURL!, "connections": []]
        upload()
    }
})

But I found the completion handler called before the upload actually finishes, I went to Firebase console and downloaded the uploaded file, it was unfinished.

Does anybody know why?

Upvotes: 0

Views: 483

Answers (1)

andih
andih

Reputation: 5603

One for your reason for your problem may be that your cache file is somehow broken. To figure it out what's happening you need more information.

You can do that by observing the FIRFileStorageUploadTaskwhich is returned by putFile.

let uploadTask = Storage.storage().reference(withPath: mediaURL!).putFile(from: localCacheURL, metadata: nil, completion: { (metadata, error) in
    if error != nil {
        print("❗️failed to upload video")
    } else {
        print("a video is uploaded")
        json = ["text": "", "image": "", "video": mediaURL!, "connections": []]
        // unclear what this does 
        // looks strange if it's just a notification rename it into something like videoUploadCompleted 
        // if it needs the json stuff pass it as parameter to make it thread safe
        upload() 
    }
})

uploadTask.observe(.progress) { snapshot in
   print("\(snapshot.progress)") 
} 

It will give you something like:

<NSProgress: 0x604000123020> :
Parent: 0x0 / Fraction completed: 0.0062 / Completed: 1867836 of
301329576

You can also get more information about failures by using

 uploadTask.observe(.failure) { snapshot in
    if let error = snapshot.error as? NSError {
      print ("Error : \(error)")
    }
}

For more details about monitoring and error handling see also Upload Files on iOS Firebase Documentation

Upvotes: 1

Related Questions