[英]How do I upload images to Firebase Storage and get link for downloadURL?
[英]Novice question, how can I return a downloadURL from firebase.Storage in swift?
准确地说,我正在使用 iOS (swiftUI)。 我正在将图像上传到firebase-storage,在每张图像上传后我已经检索了一个downloadURL,但是我一直坚持让我的urlStr(获取的downloadURL)返回。 非常感谢您的帮助。
上传然后检索 downloadURL 的代码段:
if let data = data {
mainRef.putData(data, metadata: metadata) { (metadata, error) in
if let error = error {
print("Error while uploading file: ", error)
}
if let metadata = metadata {
let pathRef = self.storage.reference(withPath: "\(dir)/\(metadata.name ?? "Image not found")")
pathRef.downloadURL { url, error in
if let error = error {
print(error.localizedDescription)
return
} else {
// Get the download URL
let urlStr:String = (url?.absoluteString) ?? ""
print(urlStr) // <--------- Pass back to newSite function.
}
}
}
}
}
return(urlReturn)
对上述内容的初始调用:
currentSite.imageMain = storageManager.upload(image: image, siteRef: newSiteRef.documentID, size: 1000, dir: "ImagesMain/")
您可以使用completion
处理程序尝试类似这种方法:
func upload(image: ....., completion: @escaping (String) -> Void) ) { // <-- here
// .....
if let data = data {
mainRef.putData(data, metadata: metadata) { (metadata, error) in
if let error = error {
print("Error while uploading file: ", error)
}
if let metadata = metadata {
let pathRef = self.storage.reference(withPath: "\(dir)/\(metadata.name ?? "Image not found")")
pathRef.downloadURL { url, error in
if let error = error {
print(error.localizedDescription)
completion("") // <-- here todo deal with errors
return
} else {
// Get the download URL
let urlStr: String = (url?.absoluteString) ?? ""
print(urlStr)
completion(urlStr) // <-- here pass back urlStr
}
}
}
}
}
return(urlReturn)
}
像这样使用它:
currentSite.imageMain = storageManager.upload(image: image, siteRef: newSiteRef.documentID,
size: 1000, dir: "ImagesMain/") { urlString in // <-- here
print("---> urlString: \(urlString)" ) // <-- here
}
由于您没有显示完整的工作示例代码,因此您必须根据需要调整方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.