将文件上传到Firebase Storage并获得downloadUrl.如何在Kotlin函数中返回结果? [英] Upload a file to Firebase Storage and get a downloadUrl. How can I return the result in a Kotlin function?

查看:126
本文介绍了将文件上传到Firebase Storage并获得downloadUrl.如何在Kotlin函数中返回结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有使用uploadTask将本地文件上传到Firestore存储的功能.我遵循了 docs 中给出的说明.这是我的代码:

I have a function that uploads a local file to Firestore Storage using uploadTask. I followed the instructions given in the docs. Here is my code:

fun uploadAudioFile(file: File){
    val audioFilePathUri = Uri.fromFile(file)
    val ref = currentUserRef.child("audioFiles/" + System.currentTimeMillis() + "." + "m4a")
    val uploadTask = ref.putFile(audioFilePathUri)

    val urlTask =
        uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }
            return@Continuation ref.downloadUrl
        }).addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val downloadUri = task.result
                Log.d("STORAGE_UTIL", "downloadUri: " + downloadUri)
            } else {
                // Handle failures
            }
        }
}

该功能可以正常工作,并呈现正确的 downloadUri .

The function works fine and renders the correct downloadUri.

现在我的问题是:我想重写此函数,以便它返回该 downloadUri .像这样:

Now my question: I want to rewrite this function so that it returns that downloadUri. Something like this:

 fun uploadAudioFile(file: File): Uri? {
    val audioFilePathUri = Uri.fromFile(file)
    val ref = currentUserRef.child("audioFiles/" + System.currentTimeMillis() + "." + "m4a")
    val uploadTask = ref.putFile(audioFilePathUri)

    val urlTask =
        uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }
            return@Continuation ref.downloadUrl
        }).addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val downloadUri = task.result
                Log.d("STORAGE_UTIL", "downloadUri: " + downloadUri)
            } else {
                // Handle failures
            }
        }
    return downloadUri 
}

这为我提供了关于return语句的 downloadUri 未解决的引用. 我该如何解决?

This gives me a unresolved reference on the return statement's downloadUri. How can I solve this?

推荐答案

由于方法的原因,您无法返回downloadUri,这是因为Firebase API是asynchronous.这意味着onComplete()函数在调用后立即返回,并且从Task返回的回调将在一段时间后调用.因此,不幸的是,无法保证需要多长时间,可能需要几百毫秒到几秒钟的时间才能获得该数据.由于该方法会立即返回,因此您要返回的downloadUri变量的值尚未从回调中填充.

There is no way you can return your downloadUri as a result of a method and this is because Firebase APIs are asynchronous. This means that onComplete() function returns immediately after it's invoked, and the callback from the Task it returns, will be called some time later. So unfortunately there are no guarantees about how long it will take, it may take from a few hundred milliseconds to a few seconds before that data is available. Because that method returns immediately, the value of your downloadUri variable you're trying to return, will not have been populated from the callback yet.

基本上,您正在尝试从异步的API同步返回值.那不是一个好主意.您应该按预期异步处理API.

Basically, you're trying to return a value synchronously from an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.

对此问题的快速解决方案是在onComplete()方法中使用downloadUri变量 only 的值.基本上,uploadAudioFile()方法中存在的所有逻辑都应在回调内移动.如果要在回调之外使用该值,建议您从此

A quick solve for this problem would be to use the value of your downloadUri variable only inside the onComplete() method. Basically, all the logic that exist inside your uploadAudioFile() method should be moved inside the callback. If you want to use that value outside the callback, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback.

这篇关于将文件上传到Firebase Storage并获得downloadUrl.如何在Kotlin函数中返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆