0

I have a UITableView in which I'm fetching image URL from API and converting it into sn image. Following is the code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let url = URL(string: imageURL)
    var image: UIImage?

    if let data = try? Data(contentsOf: url!){
        image = UIImage(data: data)! // Crashing here. it's nil
    }
}

Following is the error description. I've no clue why it's happening and can't figure it out. I've debugged and I can see that url exists and it does fetch the image url. So why does it crash? It's random crash and happens quite often. I think I've started to see this error after updating to Xcode 10. Not sure if this has something to do with Xcode or just coincidence as I've never seen this error in previous version of Xcode.

Any help?

Printing description of data:

expression produced error: error: /var/folders/57/03c16yxx1v5_bs9xtqxchnhm0000gn/T/expr22-7a390e..swift:1:65: error: use of undeclared type 'Foundation' Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer<Foundation.Data>(bitPattern: 0x124588550)!.pointee)

enter image description here

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Matt
  • 315
  • 2
  • 6
  • 20
  • Ignoring the Foundation error for now, you have a lot of issues with your code. Way too many bad uses of `!` (which is the cause of the crash). You are downloading data from the Internet on the main queue - that's very bad. Never use `Data(contentsOf:)`. Use `URLSession`. – rmaddy Sep 23 '18 at 22:57
  • Tx Maddy. Didn't realise that I was doing it wrong crash was obvious. I finally managed to figure it out with URLSession. – Matt Sep 23 '18 at 23:32

1 Answers1

0

The main issue was using Data(contentsOf:) which shouldn't be used for fetching Image from URL. Correct way is to use URLSession. After some searching found a this solution which works for me https://stackoverflow.com/a/44744511/6307359

Matt
  • 315
  • 2
  • 6
  • 20