I have a struct which gets value about background images from firebase real time database.
struct BackStruct: Identifiable {
var id = UUID()
var nameBack, imageUrl, backgroundId: String
}
The problem is that image url in Real time database is just the gs:// address of the image
I am trying to get all URLs to load image on View, but downloadURL closure cannot return string type, even doesn't see global variables in the scope. How can i solve this problem?
for data in self.dataKeys {
let name = data["nameBack"] as? String ?? ""
let imageId = data["backgroundId"] as? String ?? ""
var url = data["imageUrl"] as? String ?? ""
url = url.components(separatedBy: "appspot.com/").last ?? ""
self.storRef.child(url).downloadURL { (dURL, error) in
if let error = error {
print(error)
} else {
url = dURL?.absoluteString ?? ""
}
}
let img = BackStruct(nameBack: name, imageUrl: url, backgroundId: imageId)
self.allImages.append(img)
}
The problem is not in getting the URL, but in where you use it. Since the URL is determined asynchronously, you can only use it inside the completion handler.
So:
self.storRef.child(url).downloadURL { (dURL, error) in
if let error = error {
print(error)
} else {
url = dURL?.absoluteString ?? ""
let img = BackStruct(nameBack: name, imageUrl: url, backgroundId: imageId)
self.allImages.append(img)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.