我正在尝试使用Firebase Storage上传图像。我遇到的问题是,当我调用图像上传函数时,上传任务非常缓慢,并且实际上在进一步调用时,它最终在我的主函数中最后运行。
在继续其余功能之前,有没有办法等待storageRef.putData完成?
是否可能将压缩质量从1降低更快?
这是我的功能:
func newImageUrl(){
let key = self.itemId
guard let userID = Auth.auth().currentUser?.uid else { return }
let storageRef = Storage.storage().reference().child(userID).child("SubCategory").child(self.itemTitle!).child(key!).child("ItemImages.jpg")
guard let imageData = self.itemImage.image!.jpegData(compressionQuality: 1) else { return }
print("starting image upload!")
storageRef.putData(imageData, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
return
}
storageRef.downloadURL { (url, error) in
guard let urlStr = url else{
return
}
let urlFinal = (urlStr.absoluteString)
self.imageFinalUrl = urlFinal
}
}
}
更新的功能-
func newImageUrl(completion:@escaping((String?) -> () )) {
let key = self.itemId
guard let userID = Auth.auth().currentUser?.uid else { completion(nil) ; return }
let storageRef = Storage.storage().reference().child(userID).child("SubCategory").child(self.itemTitle!).child(key!).child("ItemImages.jpg")
guard let imageData = self.itemImage.image!.jpegData(compressionQuality: 1) else { completion(nil) ; return }
print("starting image upload!")
storageRef.putData(imageData, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
return
}
storageRef.downloadURL { (url, error) in
guard let urlStr = url else{
completion(nil)
return
}
let urlFinal = (urlStr.absoluteString)
self.imageFinalUrl = urlFinal
completion(urlFinal)
}
}
}
主要功能示例:
func updateItemDetail(){
print("this is running 1")
self.newImageUrl { (str) in
print(str)
}
print("this is running 2")
控制台打印:
this is running 1
starting image upload!
this is running 2
Optional("https://firebasestorage.googleapis.com/v0/b/.....etc")
答案 0 :(得分:1)
您需要完成
func newImageUrl(completion:@escaping((String?) -> () )) {
let key = self.itemId
guard let userID = Auth.auth().currentUser?.uid else { completion(nil) ; return }
let storageRef = Storage.storage().reference().child(userID).child("SubCategory").child(self.itemTitle!).child(key!).child("ItemImages.jpg")
guard let imageData = self.itemImage.image!.jpegData(compressionQuality: 1) else { completion(nil) ; return }
print("starting image upload!")
storageRef.putData(imageData, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
return
}
storageRef.downloadURL { (url, error) in
guard let urlStr = url else{
completion(nil)
return
}
let urlFinal = (urlStr.absoluteString)
self.imageFinalUrl = urlFinal
completion(urlFinal)
}
}
}
致电
newImageUrl { (str) in
print(str)
// do your next work here
}