为什么我的Firebase存储URL没有上传到Google Cloud Firestore?

时间:2019-08-24 15:53:54

标签: ios swift firebase google-cloud-firestore firebase-storage

我正在尝试允许用户将个人资料照片上传到Firebase Storage。图片在我的应用注册过程中上传。图像已正确上传到Firebase存储,但是下载URL未上传到Google Cloud Firestore。

我已经尝试将类型为downloadURL的变量String更改为空的String。这并没有改变结果。

以下是将个人资料照片上传到Firebase Storage的代码:

func uploadProfilePic() -> String {
     guard let imageData = profilePic?.jpegData(compressionQuality: 0.75) else {
         print("Unable to get image data.")
         return ""
     }

     let imageID = UUID().uuidString
     let profilePhotosRef = Storage.storage().reference().child("profilePhotos/\(imageID).jpg")

     let uploadMetadata = StorageMetadata()
     uploadMetadata.contentType = "image/jpeg"

     var downloadURL = String()
     profilePhotosRef.putData(imageData, metadata: uploadMetadata) { (downloadMetadata, err) in
         if let err = err {
             self.showAlertWithOK(title: "An Error Occurred", message: "There was an error uploading your profile photo. Try again later in Hostend settings.")
             print("An error occurred: \(err.localizedDescription)")
         }

         profilePhotosRef.downloadURL { (url, err) in
             if let url = url {
                 downloadURL = url.absoluteString
             }
         }
     }

     return downloadURL
}

以下是用于将个人资料照片下载网址上传到Cloud Firestore的代码:

db.collection("users").document(uid).setData(["profile_pic_url": uploadProfilePic(), "name": name, "phone_number": phoneNumber, "fcm_token": token, "timestamp": Date()])

uploadProfilePic()方法返回一个String

我希望将图像的下载URL上传到“ profile_pic_url”下的Firestore,但这没有发生。相反,即使映像已成功存储到Firebase Storage中,它也只是一个空String

1 个答案:

答案 0 :(得分:2)

您不能对包含闭包的函数使用return语句,因为该函数将在闭包执行之前返回。

改为将您的函数更改为使用补全处理程序,例如

func uploadProfilePic(completion: @escaping (String?, Error?) -> ()) {

然后,一旦获得下载网址,就调用处理程序。

    profilePhotosRef.downloadURL { (url, err) in
      completion(url, err)
    }

然后您可以像这样使用此功能来填充对Cloud Firestore的呼叫

   self.uploadProfilePic() { (url, error) in

    guard error....

    if let url = url {
      // do you upload here
    }
}