简体   繁体   English

无法快速获取downloadURL fire storage的值

[英]Cannot get value of downloadURL fire storage swift

I have a struct which gets value about background images from firebase real time database.我有一个结构,它从 firebase 实时数据库中获取有关背景图像的价值。

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问题是实时数据库中的图像 url 只是图像的 gs:// 地址

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.我正在尝试获取所有 URL 以在 View 上加载图像,但 downloadURL 闭包无法返回字符串类型,甚至在范围内看不到全局变量。 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.问题不在于获取 URL,而在于您在哪里使用它。 Since the URL is determined asynchronously, you can only use it inside the completion handler.由于 URL 是异步确定的,因此您只能在完成处理程序中使用它。

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)
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM