Peter Pik Peter Pik - 1 year ago 478
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.


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

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

Answer Source

You can do it this way:

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

   //assign your image here 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download