首页 > 解决方案 > Swift4:来自 URL 的 UIImage

问题描述

我有个问题。

我想从 url 获取图像,并在表格单元格中显示 UIimage。 let url有价值,但它变成nil

并运行此代码得到错误

Fatal error: Unexpectedly found nil while unwrapping an Optional value

为什么会有价值nil

let url = URL(string: stores![indexPath.row].photos[0].path)

    DispatchQueue.global().async {
        let data = try? Data(contentsOf: url!)
        DispatchQueue.main.async {
             cell.imageCell.image = UIImage(data: data!)
        }
    }
    return cell
}

商店![indexPath.row].photos[0].path 值

http://127.0.0.1:8000/photos/NY_0.jpeg

标签: iosjsonswiftapiuiimage

解决方案


您是否尝试将该 URL 复制并粘贴到浏览器中并查看该图像是否确实存在?

还有你使用“!” 到处都在要求崩溃。只使用“!” 当你完全确定你正在解包的东西不会是零时。

guard let stores = stores else { return cell }
guard indexPath.row < stores.count else { return cell }

if let url = URL( string:stores[indexPath.row].photos.first.path)
{
    DispatchQueue.global().async {
      if let data = try? Data( contentsOf:url)
      {
        DispatchQueue.main.async {
          cell.imageCell.image = UIImage( data:data)
        }
      }
   }
}

return cell

推荐阅读