gpt4 book ai didi

swift - 用 FirebaseStorage 关闭(UIImage→URL)

转载 作者:行者123 更新时间:2023-11-28 14:12:38 25 4
gpt4 key购买 nike

我正在使用 Firebase Auth/Storage/Firestore 创建一个新的注册过程。

这里是新注册的过程(先用Auth认证,在Firestore中注册返回的User,有图片就保存URL)过程。

static func signUp(name: String, email: String, password: String, image: UIImage?, onSuccess: @escaping () -> Void, onError: @escaping (_ errorMessage: String?) -> Void) {
Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
if error != nil {
onError(error)
return
}
guard let uid = user?.user.uid else { return }
var dict: [String: Any] = [
"name": name,
"email": email
]
// 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()
})
}

下面是一个以Storage UIImage为参数返回URL的函数类存储服务{

// 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)
}
}
})
}

注册Auth并保存到FireStore是成功的,但是当有图片的时候,尽管它存储在 Storage 中,但图像的 URL 并未保存在 Firestore 中。

storage()闭包怎么写有问题吗

最佳答案

StorageService.storage 函数是异步的,当有图像时,在没有收到 URL 响应的情况下执行插入到 firestore 的函数。您必须将要插入的函数放在 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()
}
}

关于swift - 用 FirebaseStorage 关闭(UIImage→URL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52405973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com