我正在尝试创建一个将图像上传到Firebase存储并返回其路径下载网址的功能,以便我可以将其用于应用的其他部分。
这就是函数的样子:
func uploadImage(to reference:StorageReference, image:UIImage) -> URL? {
let imageData = UIImageJPEGRepresentation(image, 0.2)
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
var downloadURL = metadata.downloadURL()
reference.putData(imageData!, metadata: metadata) { (metadata, error) in
if error != nil {
print("Couldnt upload due to \(String(describing: error))")
}
downloadURL = metadata?.downloadURL()
}
return downloadURL!
}
我似乎无法得到我想要的结果,因为downloadUrl总是返回nil。我究竟做错了什么?
答案 0 :(得分:1)
这里的问题是您的功能在上传完成之前返回。换句话说,您的函数需要返回一个回调,而不是一个普通的URL。像 -
这样的东西func uploadImage(to reference:StorageReference, image:UIImage, completion: @escaping (URL?) -> Void) {
let imageData = UIImageJPEGRepresentation(image, 0.2)
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
var downloadURL = metadata.downloadURL()
reference.putData(imageData!, metadata: metadata) { (metadata, error) in
if error != nil {
print("Couldnt upload due to \(String(describing: error))")
completion(nil)
} else {
if let downloadUrl = metadata?.downloadURL() {
completion(downloadUrl)
} else {
completion(nil)
}
}
}
}