Getting an error when trying to use the NSURL
class below, the code below is essentially trying to store an image I am pulling in from Facebook into an imageView
. The error is as follows:
value of optional type 'NSURL?' not unwrapped, did you mean to use '!' or '?'
Not sure why this is 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.
}
}
An object representing the location of a resource that bridges to URL ; use NSURL when you need reference semantics or other Foundation-specific behavior.
A requested resource couldn't be retrieved. An attempt to establish a secure connection failed for reasons that can't be expressed more specifically. A server certificate is expired, or is not yet valid. A server certificate wasn't signed by any root server.
You might see this error message if you are running an outdated version of the NetUpdate application on your Mac. To resolve the issue, simply download and install the latest version of NetUpdate. Now, restart your computer and NetUpdate should work again as expected.
The core attributes of an NSError object are an error domain (represented by a string), a domain-specific error code and a user info dictionary containing application specific information.
The NSURL constructor you're calling has got this signature:
convenience init?(string URLString: String)
? means that the constructor may not return a value, hence it is considered as an optional.
Same goes for the NSData constructor:
init?(contentsOfURL url: NSURL)
A quick fix is:
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 (unwrap) those optionals, even if you're sure that they contain a value!
You can find more infos on optionals here: link to official Apple documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With