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!