Check if url exists

I am trying to check if a url image exists using an if statement. However, trying to check it with the wrong image url, it keeps returning:

Fatal error: Zero unexpectedly found while deploying 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 { } 
+6
source share
4 answers

You can do it as follows:

 var httpUrl = subJson["image_url"].stringValue if let data = NSData(contentsOfURL: url) { //assign your image here } 
+5
source

Other answers suggest you deploy an optional option, but the real problem is that you force the option to deploy using ! despite the fact that she is nil .

When you write something! , you say: " something may be nil , but if so, I want my program to crash."

The reason nil can be returned is if the result is invalid - for example, if you are trying to extract a key from a dictionary that is not there, or if the URL does not indicate a valid image to load.

You can combine the check for nil with an if , which expands the optional parameter and returns an optional value until the value was nil . You can also combine them together, so if you need to expand the value and then pass it into a call that also returns optional, you can do it all in one if :

 if let httpUrl = subJson["image_url"].string, url = NSURL(string: httpUrl), data = NSData(contentsOfURL: url), image = UIImage(data: data) { // use image value } else { // log some error } 

Note: in the first line, calling .string , not .stringValue - .string also returns an optional parameter with nil if the value is not present.

Of course, combining all of these deployments means that you cannot say which one was unsuccessful, so you can break them down into separate statements.

+5
source

You need to deploy an optional option:

 if let image = data { // use image here } else { // the data is nil } 
+1
source

This code is verified and successful: if the image URL does not exist, you can work.

 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) } 
+1
source

Source: https://habr.com/ru/post/986277/


All Articles