Home > Software engineering >  Firebase Storage putFile() never completes when there's no internet connection
Firebase Storage putFile() never completes when there's no internet connection

Time:11-10

I've encountered one strange bug with Firebase Storage Kotlin SDK. I'm using a putFile() function to upload an image to Firebase. Everything seems to work just fine, I'm able to achieve that. However when I try to test and disable an internet connection, then that function does not return anything. I mean I've placed all UploadTask listeners, but neither one of them is called. It just keeps "loading". Has anyone had any similar issues?

val storage = FirebaseStorage.getInstance().reference
val remoteImagePath = "images/username/imageName.jpg"
val imageRef = storage.child(remoteImagePath)
val result = imageRef.putFile(image)
result.addOnSuccessListener {
    Log.d("ViewModel", "Success!")
}.addOnFailureListener { error ->
    Log.d("ViewModel", "${error.message}")
}.addOnCompleteListener{
    Log.d("ViewModel", "Completed!")
}

CodePudding user response:

However when I try to test and disable an internet connection, then that function does not return anything.

That's the expected behavior since you disabled the internet connection on your device. There is no way you can upload an image to Cloud Storage if the device is not connected to the internet.

However, The Firebase SDK for Cloud Storage supports resuming uploads. This means that once you have started to upload a file while you're online, you can resume it later. So in order to be able to resume an upload operation of a particular file, you must be online at least until the upload starts and you're able to call UploadTask.TaskSnapshot#getUploadSessionUri() to get the value of "uploadSessionUri". This URI is valid for approximately one week and can be used to resume the upload later by passing the value to StorageReference#putFile(Uri, StorageMetadata, Uri) method. Without it, you cannot resume any upload. If you need that URI object to persist across applications restarts, then you can save that object in persistent storage, such as SharedPreferences, or even better in Data Store.

So if you're offline and you didn't manage to get the session URI, then you cannot resume an upload. There is no mechanism for an auto-retry.

I mean I've placed all UploadTask listeners, but neither one of them is called.

As you already noticed, the type of object that is returned by the StorageReference#putFile(uri: Uri) method is UploadTask. So you can attach a listener to see when the operation is complete or fails with an exception. In most cases, onFailure is called when the Storage servers reject the operation due to improper security rules.

P.S.

Congrats for your video tutorials ;)

  • Related