Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if url image exist

Tags:

ios

swift

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 {
}
like image 532
Peter Pik Avatar asked Apr 30 '15 08:04

Peter Pik


2 Answers

You can do it this way:

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

   //assign your image here 
}
like image 185
Dharmesh Kheni Avatar answered Sep 26 '22 09:09

Dharmesh Kheni


This code is tested and successful: if image url not exists no crash.

let url: NSURL = NSURL(string: "http://www.example.com/images/image.png")!
    do {
        let imgData = try NSData(contentsOfURL: url, options: NSDataReadingOptions())
        ImageView?.image = UIImage(data: imgData)
    } catch {
        print(error)
    }
like image 44
Berry Finn Avatar answered Sep 23 '22 09:09

Berry Finn