storageRef.downloadURL不在内部执行代码

时间:2018-11-20 04:37:55

标签: swift xcode firebase firebase-realtime-database firebase-storage

func uploadProfileImage(_ image:UIImage, completion: @escaping ((_ url:URL?)->())) {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let storageRef = Storage.storage().reference().child("user/\(uid)")

    let imageData = image.jpegData(compressionQuality: 0.75)

    let metaData = StorageMetadata()
    metaData.contentType = "image/jpg"

    storageRef.putData(imageData!, metadata: metaData)
    //Get url
    let imageRef = storageRef
    imageRef.downloadURL { url, error in
        if let error = error {
            print(error.localizedDescription)
        }else{
            print(url.absoluteString)
        }
    }

}

里面的代码将不会执行,它将跳过所有内容,并像没有存储任何代码一样工作。我不确定补全的工作原理,但我可以想象它会打印错误或打印url,但两者都不会。当我在此处设置断点时,它甚至都不会检查error = error。我做错了什么吗?还是其他人遇到了同样的问题?

imageRef.downloadURL { url, error in
    if let error = error {
        print(error.localizedDescription)
    }else{
        print(url.absoluteString)
    }
}

2 个答案:

答案 0 :(得分:0)

您的 putData:metadata:completion:没有完成块。上传后,您可以 访问下载URL,因此putData应该如下所示。

storageRef.putData(imageData!, metadata: metaData) { (metadata, error) in
            guard let metadata = metadata else {
                // an error occurred!
                return
            }
            // Metadata contains file metadata such as size, content-type.
            let size = metadata.size

            // You can only access to download URL after upload.
            let imageRef = storageRef

            imageRef.downloadURL { (url, error) in
                guard let downloadURL = url else {
                    // an error occurred!
                    return
                }
            }
        }

答案 1 :(得分:0)

您的API调用是异步的,因此为什么您需要而不是打印的原因实际上是使用完成块来返回结果(错误或值)。