简体   繁体   中英

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

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 .

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

Here's the why : NSData 's init(contentsOfURL:) initializer takes a non-optional NSURL reference. That means you're not allowed to initialize a data object by passing nil instead of a URL — doing so would be nonsensical. (If you really want to create an empty NSData , use an initializer that's more semantically appropriate for doing that.) It also means you can't pass a reference that has the possibility of being nil — that is, an optional .

When you receive an optional, you need to check and unwrap it before passing to code that wants a non-optional reference. (See the aforelinked part of The Swift Programming Language for all the ways you can do that.) Doing this limits the number of failure points in your code — instead of having code several layers deep behind an API call breaking because you passed it something you didn't expect to, Swift pushes you to catch unexpected values before they get to be a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM