Swift - NSURL Error

Getting an error when trying to use the NSURL class below, the code below is essentially trying to save the image that I am pulling from Facebook into imageView . The error is as follows:

 value of optional type 'NSURL?' not unwrapped, did you mean to use '!' or '?' 

I don’t know why this is happening, help!

 import UIKit class ViewController: UIViewController { @IBOutlet weak var myImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture") let imageData = NSData(contentsOfURL: myProfilePictureURL) self.myImage.image = UIImage(data: imageData) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 
+6
source share
2 answers

The NSURL constructor you invoke received this signature:

 convenience init?(string URLString: String) 

? means that the constructor may not return a value, so it is considered optional .

The same goes for the NSData strong> constructor :

 init?(contentsOfURL url: NSURL) 

Quick fix:

 let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture") let imageData = NSData(contentsOfURL: myProfilePictureURL!) self.myImage.image = UIImage(data: imageData!) 

The best solution is to check (expand) these options, even if you are sure that they contain a value!

More information about the options can be found here: link to Apple's official documentation .

+6
source

As noted in the comments, the compiler tells you exactly what to do, and Xcode offers a fix to fix it.

Here's why: NSData init(contentsOfURL:) initializer accepts an optional NSURL reference. This means that you are not allowed to initialize the data object by passing nil instead of the URL - this will be pointless. (If you really want to create an empty NSData , use an initializer that is more semantically suitable for this.) This also means that you cannot pass a link that has the ability to be nil - that is, optional .

When you get an option, you need to check and expand it before moving on to code that wants to get an optional link. (See the above part of the Swift programming language for all the ways you can do this.) Doing this limits the number of points of failure in your code - instead of having the code several layers deep behind breaking the API call because you passed it to it something you did not expect Swift to make you catch unexpected values ​​before they become a problem.

0
source

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


All Articles