Swift:通过Firebase中保存的URL显示图像

问题描述 投票:0回答:1

我想在我的表格单元格中显示商店名称,描述和图像的列表,如下所示:

enter image description here

我创建了这样的故事板:

enter image description here

这就是我到目前为止所得到的:

enter image description here

我以下面的格式将数据存储在Firebase中

enter image description here

创建了适合Firebase数据的数据模型

for stores in snapshot.children.allObjects as! [DataSnapshot]{
    let storeObject = stores.value as? [String: AnyObject]
    let storeName = storeObject?["storeName"]
    let storeDesc = storeObject?["storeDesc"]
    let storeUrl = storeObject?["storeUrl"]

    let store = StoreModel(
        name: storeName as! String?, 
        desc: storeDesc as! String?, 
        url: storeUrl as! String?)

    self.storeList.append(store)
}

显示数据

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ViewControllerTableViewCell

    let store: StoreModel

    store = storeList[indexPath.row]

    cell.labelName.text = store.name
    cell.labelDesc.text = store.desc

    return cell
}

我已成功显示商店名称和说明列表,但不知道如何通过我存储在Firebase中的URL显示图像。

我在tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int函数中尝试过以下代码,但它没有用

let imageUrl:URL = URL(string: store.url)!
let imageData:NSData = NSData(contentsOf: imageUrl)!
let image = UIImage(data: imageData as Data)

cell.imageStore.image = image

错误消息:

Value of optional type 'String?' must be unwrapped to a value of type 'String'
Coalesce using '??' to provide a default when the optional value contains 'nil'
Force-unwrap using '!' to abort execution if the optional value contains 'nil'

谢谢!

ios swift firebase
1个回答
3
投票

作为建议你应该避免强制解包并使用Swift类型,例如Data而不是NSData :)然后,你尝试的代码同步工作,最好异步下载你的图像以避免阻塞UI,尝试使用URLSession,你可以创建一个UIImageView扩展,例如:

extension UIImageView {
    func setImage(from urlAddress: String?) {
        guard let urlAddress = urlAddress, let url = URL(string: urlAddress) else { return }
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil else { return }
            DispatchQueue.main.async {
                self.image = UIImage(data: data)
            }
        }
        task.resume()
    }
}

然后你可以用这种方式调用它:

cell.imageView.setImage(from: storeUrl)
© www.soinside.com 2019 - 2024. All rights reserved.