-1

I'm trying to add downloaded images to imageViews in a tableView cell. The images that are downloaded have urls in an array "articles".

I have written a function which downloads the image depending on the urls stored in an array:

     let urlRequest = URLRequest(url: URL(string: url)!)

        let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if error != nil {
                print("error")
                return
            }
            DispatchQueue.main.async {
                self.image = UIImage(data: data!)
            }
        }
        task.resume()
    }
}

Then, in the cellForRowAtIndexPath method :

    var imageData = self.articles?[indexPath.item].imageUrl

    cell.imgView.downloadImage(from: imageData!)

However, this gives me the error: "Unexpectedly found nil while unwrapping an Optional value" in the line:

    cell.imgView.downloadImage(from: imageData!)

How do you fix this problem?

AVerguno
  • 1,277
  • 11
  • 27

2 Answers2

0

Depending on where you have the download code, and how long it actually takes, you most likely haven't loaded the images when you try to display the tableView.

You need to put a check in cellForRowAtIndexPath to only use the image if it is != nil, and then in the closure of the download, add tableView.reloadData()

Russell
  • 5,436
  • 2
  • 19
  • 27
0

First of all please tell me all urls in articles array are valid or not or there is any empty url or not. Further more you can resolve the error by updating your file download method

let urlRequest = URLRequest(url: URL(string: url)!)

        let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if error != nil {
                print("error")
                return
            }
            DispatchQueue.main.async {

                if let _image = UIImage(data: data!) {
                 self.image = UIImage(data: data!)
                }

            }
        }
        task.resume()
    }

Basically your error occurs when you try to get image from data and there data will be nil. So by adding If-let you can resolve your error.

Usman Javed
  • 2,437
  • 1
  • 17
  • 26