我试图允许用户将个人资料照片上传到 Firebase Storage。该图像是在我的应用程序的注册过程中上传的。图片已正确上传到 Firebase Storage,但是下载网址未上传到 Google Cloud Firestore。
我已经尝试更改 String
类型的变量 downloadURL
以保存空的 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
}
以下是将个人资料照片下载 URL 上传到 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 存储,它也只是一个空的String
。
最佳答案
不能对包含闭包的函数使用 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 your upload here
}
}
关于ios - 为什么我的 Firebase 存储网址没有上传到 Google Cloud Firestore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57639456/