Swift4:来自 URL 的 UIImage

Swift4: UIImage from URL

我有问题。

我想从 url 获取图像,并在 table 单元格中显示 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].照片[0].路径值

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

您是否尝试过将 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