2017-06-01 59 views
1

通過Firebase存儲上傳文件時,onSuccess方法未調用。Firebase存儲的OnSuccessListener回調未調用

我目前使用'com.google.firebase:firebase-storage:10.2.6'運行Android Studio 3.0 Canary 2。

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()) 
       } 
      } 
     } 
    } 

回答

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()) 
}