我正在尝试将图像上传到Firebase存储器并获取下载网址以将其保存在数据库中,但是我得到了一个nil值,并且该函数在检查后返回。我遵循了其他文章中的文档和解决方案,但看不到错误之处。 功能是:
long count = collection.count(new Document("sent", new Document("$exists", true)));
if (count < 5) { // if the number of documents less than 5 has field named as sent
// then to do something
}
您看到错误在哪里吗? 非常感谢。
答案 0 :(得分:0)
考虑到这一点,我意识到downloadURL
的获取实际上是在图像上传完成之前完成的,这是因为Firebase是异步的。因此,我在上传部分添加了completion block
,在completion scope
中放入了downloadURL
获取部分。
它不会眨眼,我会很乐意提速的建议,因为这样可以在segue
执行之前有一点滞后。
我可以而且可能应该添加一点旋转按钮来向用户显示该应用程序尚未冻结,这一点也不令人烦恼,但我宁愿尽可能地完全避免延迟。我离开prints
的目的是希望这篇文章能对Firebase的新人有所帮助,并提供详细的几乎逐步的指导,因为这种答案以前确实对我有帮助,但是我没有找到任何关于这个问题。
改写的功能是:
func uploadImage(completed: @escaping (Bool) -> (),_ image: UIImage ){
print(" ############## UPLOAD STARTED ###########")
// Create a root reference
let storageRef = Storage.storage().reference()
// Create a reference to Images folder
let alertsImagesRef = storageRef.child("Alert Images")
// Create a reference for new images
let uuid = UUID()
let imageRef = alertsImagesRef.child("userAlertImage \(uuid).jpg")
let imageData = UIImageJPEGRepresentation(image, 0.5)
let metaData = StorageMetadata()
metaData.contentType = " jpeg " // data type
metaData.customMetadata = ["k1": "",
"k2" : " ",
"k3" : "",
"k4" : ""]
imageRef.putData(imageData! as Data , metadata: metaData, completion: { metaData, error in
if(error != nil){
print(error as Any)
return
}
print(" ####### image uploaded #######")
self.tapCounter = 0
self.performSegue(withIdentifier: "chooseIconSegue", sender: self)
// fetch url v2
imageRef.downloadURL(completion: { (url, err) in
if let err = err {
print("Error downloading image file, \(err.localizedDescription)")
return
}
guard let url = url else { return }
//Now you have the download URL for the image, and can do whatever you want with it.
NewMapViewController.alertImageURL = url.absoluteString
print(" ######### url is:\(String(describing: url)) #########")
completed(true)
// self.postAlertNotification()
// self.tapCounter = 0
// self.performSegue(withIdentifier: "chooseIconSegue", sender: self)
print(" ############## UPLOAD ENDED ###########")
})
})
}