我正在使用Firebase身份验证/存储/ Firestore创建新的注册过程。
这是新注册的过程(首先通过Auth进行身份验证,在Firestore中注册返回的用户,如果有图片则保存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的功能 StorageService {
类// 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,但是当有映像时, 尽管图像存储在存储中,但图像的URL并未保存在Firestore中。
storage()如何编写闭包?
答案 0 :(得分:1)
函数StorageService.storage
是异步的,当有图像时,将执行插入到Firestore中的函数,而不会收到URL响应。
您必须将函数插入StorageService.storage
中以获取并保存图像的网址
// 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()
}
}