【问题标题】:Swift4: UIImage from URLSwift4:来自 URL 的 UIImage
【发布时间】:2018-08-21 03:20:11
【问题描述】:

我有问题。

我想从 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 使用 Data(contentsOf: URL) 初始化程序。你不应该同步下载这些。
  • 127.0.0.1:8000/photos/NY_0.jpeg 看起来不是一个有效的网址
  • 代码似乎应该可以工作。但是,您使用本地 API 来获取图像,Check if AppTransportSecurity is allowing you to make the request
  • @kathayatnk 我设置了AppTransportSecurity 但值为零
  • 你确定stores![indexPath.row].photos[0].path 确实有http://127.0.0.1:8000/photos/NY_0.jpeg 的准确值吗?这是一个完全有效的 URL,并且 not 会导致 url 成为 nil。确保值中没有空格。

标签: ios json swift api uiimage


【解决方案1】:

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

【讨论】:

  • 是的,我已检查是否从该 URL 获取图像。
  • 粘贴这段代码,我在guard let stores = stores else { return }guard indexPath.row &lt; stores.count else { return } 部分出现错误。错误Non-void function should return a value
  • @Alex :错误是因为您没有从您的方法中返回单元格,就像您的问题一样。
  • 如@kathayatnk 所指出的,已通过返回单元格更新了我的答案
猜你喜欢
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多