Swift - NSURL error

只谈情不闲聊 提交于 2019-11-30 21:11:54

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!