Firebase 存储上传任务继续永远不会触发



我正在处理一个项目,我需要将图像上传到 Firebase 存储并获取下载网址,然后才能将关联的模型类上传到 Firestore。

我正在尝试使用倒计时闩锁来阻止主线程,直到上传完成。我知道有更好的方法,并随时推荐一些,但我想我可以通过一个简短的加载屏幕。问题是 getDownloadurl 任务的回调永远不会被调用。我搜索了又搜索,但想不通。现在我的代码直接来自文档。

fun uploadListing(listing: Listing, images: ArrayList<ByteArray>, onCompleteListener: () -> Unit = {}) {
            val listingRef = FirebaseFirestore.getInstance().collection(LISTINGS_COLLECTION).document()
            val storageRef = FirebaseStorage.getInstance().reference
            listing.id = listingRef.id
            val countDownLatch = CountDownLatch(images.size)
            var i = 0
            images.forEach {
                val imageRef = storageRef.child("images/${listing.id}/$i")
                val uploadTask = imageRef.putBytes(it)
                uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
                    if (!task.isSuccessful) {
                        task.exception?.let { exception ->
                            throw exception
                        }
                    }
                    return@Continuation imageRef.downloadUrl
                }).addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        listing.images.add(task.result.toString())
                        countDownLatch.countDown()
                    } else {
                        // Handle failures
                        // ...
                    }
                }
            }
            countDownLatch.await()
            listingRef.set(listing).addOnSuccessListener {
                onCompleteListener()
            }
        }

我的等级依赖...

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.google.firebase:firebase-firestore:17.1.5'
    implementation 'com.google.firebase:firebase-storage:16.0.5'
    implementation 'com.google.firebase:firebase-auth:16.1.0'
    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.squareup.picasso:picasso:2.5.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//    implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:6.5.3'
    implementation 'com.google.code.gson:gson:2.8.5'
}
永远不要

阻塞主线程。 这通常是一个糟糕的主意(正如您刚刚发现的那样),可能会导致您的应用程序因 ANR 而崩溃。

如果要在一堆任务完成时注册另一个回调,请使用 Tasks.whenAll() 的变体之一,并在移动到下一个工作项之前将要完成的所有任务传递给它。

最新更新