Swift 使用FirebaseStorage(UIImage&x2192;URL)关闭
我正在使用Firebase Auth/Storage/Firestore创建一个新的注册过程 下面是新注册的过程(首先使用Auth进行身份验证,在Firestore中注册返回的用户,如果有图像,则保存URL)过程 以下是将存储UIImage作为参数并返回URL的函数 类存储服务{Swift 使用FirebaseStorage(UIImage&x2192;URL)关闭,swift,firebase,google-cloud-firestore,firebase-storage,Swift,Firebase,Google Cloud Firestore,Firebase Storage,我正在使用Firebase Auth/Storage/Firestore创建一个新的注册过程 下面是新注册的过程(首先使用Auth进行身份验证,在Firestore中注册返回的用户,如果有图像,则保存URL)过程 以下是将存储UIImage作为参数并返回URL的函数 类存储服务{ // Upload Image to Storage static func storage(image: UIImage?, path: PathType, id: String, completion:
// Upload Image to Storage
static func storage(image: UIImage?, path: PathType, id: String, completion: @escaping (_ imageUrl: String?) -> ()) {
guard let image = image, let imageData = UIImageJPEGRepresentation(image, 0.1) else {
print("Non Image")
completion(nil)
return
}
let storageRef = Storage.storage().reference().child(path.rawValue).child(id)
storageRef.putData(imageData, metadata: nil, completion: { (metaData, error) in
if let error = error {
print("Fail to Put Data in Storage : \(error)")
completion(nil)
return
}
storageRef.downloadURL { (imageUrl, error) in
if let error = error {
print("Fail to Download Url : \(error)")
completion(nil)
return
}
if let imageUrl = imageUrl?.absoluteString {
completion(imageUrl)
}
}
})
}
}
已成功注册身份验证并保存到FireStore,但如果有图像,
尽管图像存储在存储器中,但图像的URL不会保存在Firestore中
存储()如何编写闭包有问题吗?函数
StorageService。存储是异步的,当存在映像时,要插入firestore的函数将在不接收URL响应的情况下执行。
您必须将要插入的函数放入StorageService.storage
的克隆中,才能获取并保存图像的URL
// If Image is Set
if let image = image {
StorageService.storage(image: image, path: .icon, id: uid) { (imageUrl) in
dict["iconUrl"] = imageUrl
Firestore.firestore().collection("users").document(uid).setData(dict) { (error) in
if let error = error {
print(error)
return
}
onSuccess()
}
}
}else {
Firestore.firestore().collection("users").document(uid).setData(dict) { (error) in
if let error = error {
print(error)
return
}
onSuccess()
}
}
// If Image is Set
if let image = image {
StorageService.storage(image: image, path: .icon, id: uid) { (imageUrl) in
dict["iconUrl"] = imageUrl
Firestore.firestore().collection("users").document(uid).setData(dict) { (error) in
if let error = error {
print(error)
return
}
onSuccess()
}
}
}else {
Firestore.firestore().collection("users").document(uid).setData(dict) { (error) in
if let error = error {
print(error)
return
}
onSuccess()
}
}