TableView default function:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[(indexPath as NSIndexPath).row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
cell.request?.cancel()
var img: UIImage?
if let url = post.imageUrl {
img = FeedVC.imageCache.object(forKey: url as AnyObject) as? UIImage
}
cell.configureCell(post, img: img)
return cell
} else {
return PostCell()
}
}
Configure Cell function:
func configureCell(movie: Movie, img: UIImage?){
self.movieTitle.text = movie.title
self.movieCaption.text = movie.caption
if movie.imgURL != nil {
if img != nil {
self.movieImg.image = img
}
else {
let url = movie.imgURL
request = Alamofire.request(url!).response { response in
let img = UIImage(data: response.data!)! //always returns with "fatal error: unexpectedly found nil while unwrapping an Optional value"
self.movieImg.image = img
ViewController.imageCache.setObject(img, forKey: url as AnyObject)
}
}
}
else {
self.movieImg.isHidden = true
}
}
For some reason, whenever I run this code, it always crashes and the output is:
fatal error: unexpectedly found nil while unwrapping an Optional value.
This is on the configure cell function when I set the image to UIImage(data)
. I have tried many scenarios but am failing to figure out what my problem is.