将图像从Firebase加载到我的表视图时出错

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

我想将我的图像从Firebase加载到我的表视图但是我收到错误:

无法将“String”类型的值转换为预期的参数类型“URL”

当我自己打印对象时,它肯定是一个URL。

这就是我的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "FeedItem", for: indexPath) as! FeedItem

    //TODO: Guard...

    let postImage = postArray [indexPath.row]
    let postImageURL = postImage.postImageURL
    let data = Data(contentsOf: postImageURL) // Line with Error

    cell.postImage.image = UIImage (data: data)
    return cell
}
ios swift uitableview
1个回答
1
投票

要在单元格中显示图像,您需要将URL字符串转换为实际的URL对象,您可以通过以下方式执行此操作:

let postImage = postArray[indexPath.row]
if let postImageURL = URL(string: postImage.postImageURL)
{
    do {
         let data = try Data(contentsOf: postImageURL)
         cell.postImage.image = UIImage (data: data)
    } catch {
         print("error with fetching from \(postImageURL.absoluteString) - \(error)")
    }
}

正如rmaddy暗示的那样,你的表现不会很好(因为取决于远程服务器的距离或互联网的速度有多慢),同步“Data(contentsOf:”调用可能会花费不可接受的长时间才能成功。我只是提供这个答案,所以你可以在自己的测试中看到一些东西,但我不会在生产代码中使用它。

尝试用异步Data任务替换URLSession fetch,你可以找到更多信息in this very related question

© www.soinside.com 2019 - 2024. All rights reserved.