-1

This question might be a duplicate, but I think my case is different.

I built an app to fetch news articles from different sources. The problem I have is some sources may not include article image which causing my app to crash, please have a look at my code:

extension UIImageView {
    func downloadImage(from url: String) {
        let urlRequest = URLRequest(url: URL(string: url)!) // I get Fatal error on this line
        let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

            if error != nil {
                print(error as Any)
                return
            }

            DispatchQueue.main.async {
                self.image = UIImage(data: data!)
            }
        }
        task.resume()
    }

}

I tried to modify the code to not force unwrap the image if found nil, but It just didn't work, because I get other errors in other places.

If anyone can point the mistake, please, by writing how the code should be in case image found nil to not crash the app. It will be extremely appreciated!

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Anas Khateeb
  • 76
  • 1
  • 9

3 Answers3

1

The URL is force unwrapped. You should unwrap optional by using guard let construction:

guard let url = URL(string: url) else { return }
let urlRequest = URLRequest(url: url)
Ilya Kharabet
  • 4,203
  • 3
  • 15
  • 29
0

I tried to modify the code to not force unwrap the image if found nil,

Well yes it's duplicated question.

However this problem is solved by OptionalChaining i recommend reading about it Here,

Now for the part on how to solve it quickly, you can try to add this line under your request, which is going to check if its nil or not, and incase it was nil it will simply escape the closure without causing any crashes or problems.

guard let data = data else {return} 

There are many types of OptionalChaining, each one has its own usage but they all serve the same propose of handling the nil values without causing a crashes.

Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
-1
DispatchQueue.main.async {

    guard let data = data {

        self.image = UIImage(data: data)

    } else {

        print(value is nil.)

    }
}
  • This is the way to safe unwrap the optional value. It will not crash if Data is nil on unwrapping .
siburb
  • 4,880
  • 1
  • 25
  • 34
Prabhat
  • 76
  • 3
  • add more details, and fix the answer format. – Mohmmad S Oct 17 '18 at 07:19
  • @Tobi I only suggesting optional chaining for unwrapping optional values. Please go through below link. [https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html] – Prabhat Oct 17 '18 at 08:07