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

时间:2019-03-17 11:22:40

标签: ios swift firebase

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

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'

谢谢!

1 个答案:

答案 0 :(得分: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)