Peter Pik Peter Pik - 6 months ago 209
Swift Question

Check if url image exist

I'm trying to check if a url image exist using a if statement. However when trying to test it by wrong image url it keep returning:


fatal error: unexpectedly found nil while unwrapping an Optional value.


code:

var httpUrl = subJson["image_url"].stringValue
let url = NSURL(string: httpUrl)
let data = NSData(contentsOfURL: url!)

if UIImage(data: data!) != nil {
}

Answer

You can do it this way:

var httpUrl = subJson["image_url"].stringValue
if let data = NSData(contentsOfURL: url) {

   //assign your image here 
}
Comments