iosjsonswiftuiimage

Swift4: UIImage from URL


I have a problem.

I want to get the image from URL, and display UIimage in table cell. let url has value but it becomes nil.

And run this code got error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

Why will the value be 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

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


Solution

  • Did you try copying and pasting that URL into a browser and see if the image really does exist?

    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