云存储:downloadUrl类型不匹配:推断类型为Task 但是Uri!预期

问题描述 投票:0回答:1

我刚刚开始与Kotlin学习android开发。我正在尝试在我的项目中实现MVVM。

消息:类型不匹配。必填:Uri!找到:任务

我有一个问题:如何在网址中投放任务! ???

我有ViewModel:

class AddVehicleViewModel(private val vehicleRepository: VehicleRepository,
                          onFailureListener: OnFailureListener): BaseViewModel(onFailureListener) {
    private val _mkVehicleCompletedEvent = SingleLiveEvent<Unit>()
    val mkVehicleCompletedEvent = _mkVehicleCompletedEvent
    val user = vehicleRepository.getUser()

    fun mkVehicle(user: User, imageUri: Uri?, auto: String) {
        if (imageUri != null) {
            vehicleRepository.uploadVehicleImage(user.uid, imageUri).onSuccessTask { downloadUrl ->
                Tasks.whenAll(
                    vehicleRepository.createVehicle(user.uid, mkListVehicle(user, auto, downloadUrl.toString()))
                )
            }.addOnCompleteListener {
                _mkVehicleCompletedEvent.call()
            }.addOnFailureListener(onFailureListener)
        }
    }

    private fun mkListVehicle(user: User, auto: String, imageUri: String): DataVehicles {
        return DataVehicles(
            uid = user.uid,
            image = imageUri,
            auto = auto,
            username = user.username,
            city = user.city.toString()
        )
    }
}

和存储库:

class FirebaseVehicleRepository : VehicleRepository {
    override fun uploadVehicleImage(uid: String, imageUri: Uri): Task<Uri> =
        task { taskSource ->
            storage.child("users").child(uid).child("images")
                .child(imageUri.lastPathSegment.toString()).putFile(imageUri).addOnCompleteListener {
                if (it.isSuccessful) {
                    taskSource.setResult(it.result!!.metadata!!.reference!!.downloadUrl)
                } else {
                    taskSource.setException(it.exception!!)
                }
            }
        }

错误在此代码行上闪烁:

taskSource.setResult(it.result!!.metadata!!.reference!!.downloadUrl)
firebase kotlin mvvm firebase-storage
1个回答
0
投票

您不会将任务投放到Uri。 “属性” downloadUrl实际上是一个异步Java方法,称为getDownloadUrl(),它返回一个Task。您需要在Task上使用一个侦听器来获取Uri,就像调用putFile()时所做的一样,该C0还返回Task。

使用documentation中显示的图案:

storageRef.child("users/me/profile.png").downloadUrl.addOnSuccessListener {
    // Got the download URL for 'users/me/profile.png'
}.addOnFailureListener {
    // Handle any errors
}

根据您的情况,使用it.result!!.metadata!!.reference!!.downloadUrl.addOnSuccessListener ...

另请参见等效的Java语言:How to get URL from Firebase Storage getDownloadURL

© www.soinside.com 2019 - 2024. All rights reserved.