swift:firebase putData和downloadUrl延迟返回URL-太迟了

时间:2019-08-29 13:41:46

标签: swift firebase firebase-storage

简而言之,我正在按照以下顺序编写应用。

  1. 将图像上传到Firebase存储。
  2. 下载图像URL。
  3. 将URL(和其他一些人员)上传到Firestore文档。

第1部分和第3部分运行良好。除了我收到URL太晚的事实之外。是的,为时已晚。

要了解发生了什么,我以预期的顺序0-13添加了打印语句。请参阅下面的代码。打印语句9-13在函数uploadImage之外。

执行应用程序时,处理后的订单如下:

0-调用函数uploadImage之前

1-就在putData之前

8-离开功能uploadImage之前

12-上载带有URL的文档:Optional(“”)

13-在FirestoreDB.collection.addDocument->添加了ID为3uDhNM3o的文档...

2-处理putData的完成

4-在下载URL之前

5-处理下载URL的完成

7-在完成网址https://firebasestorage.googleapis.com/之内…

10-在uploadImage函数的复制网址内

11a-可用的网址https://firebasestorage.googleapis.com/ ...

有什么建议吗? 谢谢迈克尔

        guard let imageData = image.jpegData(compressionQuality: 0.2) else {
            completion(nil)
            return
        }

        let uploadStorageReference = storageReference.child(directory)
        let imgID = NSUUID().uuidString
        let idStorageReference = uploadStorageReference.child(imgID)
        let metaData = StorageMetadata()
        metaData.contentType = "image/jpeg"

        print("1 - Right before putData")
        _ = idStorageReference.putData(imageData, metadata: metaData, completion: { (metadata, error) in
            print("2 - Processing the completion of putData")
            if let error = error {
                print("3 - Within error handling of putData \(error.localizedDescription)")
                completion(nil)
                return
            } else {
                print("4 - Right before downloadURL")
                idStorageReference.downloadURL(completion: { (url, error) in
                    print("5 - Processing the completion of downloadURL")
                    if let error = error {
                        print("6 - Within error handling of downloadURL \(error.localizedDescription)")
                        completion(nil)
                        return
                    } else {
                        if let downloadedURL = url {
                            print("7 - Within completion url \(downloadedURL)")
                            completion(downloadedURL)
                        }
                    }
                })
            }
        })
        print("8 - Before leaving function uploadImage")
    }

1 个答案:

答案 0 :(得分:0)

Larme mentions in a comment

  

这个命令对我来说并不奇怪。您正在看到异步的概念。看如何管理它。通常在1之后打印8。

我使用DispatchSemaphore修复了它。