Peter Pik Peter Pik - 1 year ago 342
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 {


You can do it this way:

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

   //assign your image here