ios - 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
解决方案
您是否尝试将该 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
推荐阅读
- python - Anaconda/Docker 容器中未提供 Flask
- printing - 在文件比较期间删除行而不删除行号或注入新的空行
- r - 转换为具有单列的 data.frame 后在 ggplot 中绘图?
- c# - 从 LinkedList 中删除给定位置的元素
- alignment - 如何在运行时 C++ Builder 中在 Fire Monkey 多设备应用程序中设置对齐?
- java - 如何从文本文件中读取并移至下一行
- iis - Windows Server 2016 IIS 10 上的 Webapi 404
- bash - 如何使用 awk 将目录添加到变量中的文件列表中?
- dart - 如何从 StreamBuilder 获取 StreamSubscription
- c# - DataGridView 列排序方向始终为 asc