0

My app which I have made in swift 4 crashes when a news provider does not have an image! So when I scroll over an article which does not have an image it crashes and I get the error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Here is my code for the image:

let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {
    func downloadImage(from url: String){
    let urlRequest = URLRequest(url: URL(string: url)!)
    image = nil
    if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage {
        self.image = imageFromCache
        return
    }
    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
        if error != nil {
            print(error!)
            return
        }    
        DispatchQueue.main.async {
            let imageToCache = UIImage(data: data!)
            imageCache.setObject(imageToCache!, forKey: url as AnyObject)
            self.image = imageToCache
        }
    }
    task.resume()
    }
}
Gaurav Bharti
  • 1,065
  • 1
  • 14
  • 22
Techitout
  • 37
  • 1
  • 7
  • Which line is crashing? And why do you have so many crash operators (`!`) in your code? – rmaddy Mar 09 '18 at 17:53
  • @rmaddy imageCaching.setObject(imageToCache!, forKey: url as AnyObject) **That is the line that is crashing** – Techitout Mar 09 '18 at 18:21
  • It seems like you've provided the answer as part of the question. If you don't have an image, don't try to use it as if you did. – Phillip Mills Mar 09 '18 at 19:14
  • @PhillipMills So if it doesn’t find an image from the Json file it crashes basically – Techitout Mar 09 '18 at 19:34
  • Only if you use something like `imageToCache!` to guarantee that the value won't be nil. You broke your promise; it crashed. :) – Phillip Mills Mar 09 '18 at 20:03
  • @PhillipMills I would like some help. I’m really new to swift – Techitout Mar 09 '18 at 20:06
  • 1
    I think your best source of help would be to read about Swift Optionals. Whenever you use `!`, you're saying that even though it's an optional value you **KNOW** it's not nil. In other words, don't do that unless you must. Use `if let` to test whether you have something valid or not. – Phillip Mills Mar 09 '18 at 20:13

0 Answers0