问题
Why ever function return nil?! I try add DispathQue but I don't understand how it should be right! Pls Help
func storagePutData(uid: String, image: UIImage, compretition: @escaping (Error?) -> Void) -> String {
var downloadURL: String!
let imageName = NSUUID().uuidString
let uploadDara = UIImageJPEGRepresentation(image, 0.1)!
let ref = self.refStorage.child("usersProfileImage/\(uid)/\(imageName).png")
ref.putData(uploadDara, metadata: nil) { (metaDara, error) in
if let err = error {
compretition(err)
}
ref.downloadURL(completion: { (url, error) in
if let err = error {
compretition(err)
} else {
downloadURL = url?.absoluteString
}
})
}
return downloadURL
}
回答1:
You're returning downloadURL
before the asynchronous function within your callee function has finished execution.
At this point, it will have nil
value, which is correct.
You'll want to use a completion handler to return downloadURL
when its ready, like -
func storagePutData(uid: String, image: UIImage, success:@escaping (String?)->(), error: @escaping (Error?) -> Void) {
var downloadURL: String!
let imageName = NSUUID().uuidString
let uploadDara = UIImageJPEGRepresentation(image, 0.1)!
let ref = self.refStorage.child("usersProfileImage/\(uid)/\(imageName).png")
ref.putData(uploadDara, metadata: nil) { (metaDara, error) in
if let err = error {
error(err)
}
ref.downloadURL(completion: { (url, error) in
if let err = error {
error(err)
} else {
downloadURL = url?.absoluteString
success(downloadURL)
}
})
}
}
来源:https://stackoverflow.com/questions/52483163/why-function-return-nil-firebase-swift