问题
I am creating a new registration process using Firebase Auth / Storage / Firestore.
Here is the process of new registration (first authenticate with Auth, register the returned User in Firestore, save the URL if there is an image) process.
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()
})
}
The following is a function of taking the Storage UIImage as an argument and returning the URL class 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)
}
}
})
}
}
Registration of Auth and saving to FireStore are successful, but when there is an image, Although it is stored in Storage, the URL of the image is not saved in the Firestore.
storage () Is there a problem with how to write a closure?
回答1:
The function StorageService.storage
is asynchronous, when there is an image, the function to insert in the firestore is executed without receiving the URL response.
You must place your function to insert in the clousure of StorageService.storage
to get and save the URL of the image
// 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()
}
}
来源:https://stackoverflow.com/questions/52405973/closure-with-firebasestorage-uiimage%e2%86%92url