简体   繁体   English

Swift4:URL中的UIImage

[英]Swift4: UIImage from URL

I have a problem. 我有个问题。

I want to get the image from url, and display UIimage in table cell. 我想从url获取图像,并在表单元格中显示UIimage。 let url has value but it becomes nil let url有值,但它变为nil

And run this code got error 并运行此代码得到错误

Fatal error: Unexpectedly found nil while unwrapping an Optional value

Why will the value be nil ? 为什么值将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
}

stores![indexPath.row].photos[0].path value stores![indexPath.row] .photos [0] .path值

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

Did you try copying and pasting that URL into a browser and see if the image really does exist? 您是否尝试过将该URL复制并粘贴到浏览器中,然后查看图像是否确实存在?

Also your use of "!" 您也使用“!” everywhere is asking for a crash. 到处都在要求坠机。 Only use "!" 仅使用“!” when you are absolutely sure that what you are unwrapping is not going to be nil. 当您完全确定要展开的内容不会为零时。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM