Swift 我试图获取上传到存储器的图像的url,我发现的代码非常旧
我尝试获取上传到存储器441c-a2d8-cfb55cf8498d的图像的url 我在互联网上搜索了很多,但我只找到了旧的出版物。我找到的最新出版物向我显示了此代码,但当我执行它时,它没有进入,代码的内部部分被跳过Swift 我试图获取上传到存储器的图像的url,我发现的代码非常旧,swift,image,firebase,url,firebase-storage,Swift,Image,Firebase,Url,Firebase Storage,我尝试获取上传到存储器441c-a2d8-cfb55cf8498d的图像的url 我在互联网上搜索了很多,但我只找到了旧的出版物。我找到的最新出版物向我显示了此代码,但当我执行它时,它没有进入,代码的内部部分被跳过 let db = Firestore.firestore() let newDocument = db.collection("pets").document() pid = newDocument.documentID
let db = Firestore.firestore()
let newDocument = db.collection("pets").document()
pid = newDocument.documentID
pid = newDocument.documentID
let pidJPG = pid + ".jpg"
let storageRef = RefStorage.petImages.reference().child(pidJPG)
if let uploadData = self.imagePet?.jpegData(compressionQuality: 0.2){
storageRef.putData(uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("error: \(String(describing: error))")
return
}
}
urlImagePet = storageRef.description
storageRef.downloadURL(completion: {(url, error) in
if error != nil {
print(error!.localizedDescription)
return
}
self.image = url!.absoluteString
})
}
db.collection("pets").document(pid).setData(toDictionary()) { err in
if let err = err {
print("\n--------------------------------------")
print("Error writing document: \(err)")
print("--------------------------------------\n")
} else {
print("\n--------------------------------------")
print("Document successfully written!")
print("--------------------------------------\n")
}
}
}
func toDictionary() -> [String : Any]{
return[
"pid" : pid,
"urlImagePet" : urlImagePet,
"image" : image
]
}
对putData、downloadURL和setData的调用都是异步的。这意味着这些调用的结果仅在它们的完成处理程序中可用。要正确使用这些结果,您需要嵌套调用,就像您已经为错误处理所做的那样
比如:
if let uploadData = self.imagePet?.jpegData(compressionQuality: 0.2) {
storageRef.putData(uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("error: \(String(describing: error))")
return
}
// once you get here, the data is uploaded to Cloud Storage, and
// you can get the download URL
storageRef.downloadURL(completion: {(url, error) in
if error != nil {
print(error!.localizedDescription)
return
}
// once you get here, you have the download URL, so you can
// write it to the database
let data = [
"pid" : newDocument.documentID,
"urlImagePet" : storageRef.description,
"image" : url!.absoluteString
]
newDocument.setData(data) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
})
}
}
urlmagepet=storageRef.description保存gs://…,但我需要https://...,我只是尝试了不同的选项,我需要urlmagepet和图片https://If 在storageRef.downloadURLcompletion:完成处理程序中,您可以打印url!。absoluteString,你知道URL吗?不,我不能在里面打印,@FrankvanPuffelen,你能告诉我两个URL的区别吗?谢谢。你是对的,这对我来说非常有效。