Firebase存储的OnSuccessListener回调未调用

时间:2017-06-01 21:50:48

标签: android firebase kotlin firebase-storage

通过Firebase存储上传文件时,onSuccess方法未调用。

我目前正在运行Android Studio 3.0 Canary 2,其中包含'com.google.firebase:firebase-storage:10.2.6'。

fun uploadImage(pathToImage: String, downloadCallback: FirebaseCallback<String?>) {
        val file = Uri.fromFile(File(pathToImage))
        val ref = mStorRef.child("images/"+file.lastPathSegment)

        ref.putFile(file).addOnSuccessListener {
            object : OnSuccessListener<UploadTask.TaskSnapshot> {
                override fun onSuccess(taskSnapshot: UploadTask.TaskSnapshot?) {
                    val url = taskSnapshot?.downloadUrl
                    Log.d("FirebaseManager", "Upload Successful")
                    downloadCallback.callback(url.toString())
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

使用{},您通过SAM conversion传入lambda作为侦听器。在这个lambda中,你要定义成功会发生什么:你创建了一个从未使用过的object。要传入object作为听众,请使用()

ref.putFile(file).addOnSuccessListener (
    object : OnSuccessListener<UploadTask.TaskSnapshot> {
        override fun onSuccess(taskSnapshot: UploadTask.TaskSnapshot?) {
            val url = taskSnapshot?.downloadUrl
            Log.d("FirebaseManager", "Upload Successful")
            downloadCallback.callback(url.toString())
        }
    }
)

或者仅使用SAM转换,而无需明确创建object

ref.putFile(file).addOnSuccessListener { taskSnapshot ->
    val url = taskSnapshot?.downloadUrl
    Log.d("FirebaseManager", "Upload Successful")
    downloadCallback.callback(url.toString())
}