Search code examples
iosswiftnsurl

Swift - NSURL error


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.
    }
}

Solution

  • 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.