EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) with dataTaskWithUrl

邮差的信 提交于 2019-11-29 12:10:43
matt

I know the url is valid

The URL is not valid. You do not know what you think you know. Listen to the runtime. It knows more than you do.

Just try this code alone (in a playground, for instance):

var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.7873589,-122.408227&radius=4000&types=aquarium|art_gallery&key=YOURKEY"
let url = NSURL(string:urlString)

url is nil. And that's your problem. You cannot force-unwrap nil; you will crash if you do.

Once you acknowledge this, you can start to think about why the URL is not valid. (It's pretty obvious why that might be.) Learning to believe the compiler and the runtime is key to successful programming.

HINT: Form your URL like this and all is well:

let url2 = NSURL(scheme: "https", host: "maps.googleapis.com", path: "/maps/api/place/nearbysearch/json?location=37.7873589,-122.408227&radius=4000&types=aquarium|art_gallery&key=YOURKEY")

Why do you suppose that is? Look at the docs and see what this initializer does for you...

I would use .stringByAddingPercentEscapesUsingEncoding()

var urlString = "http://example.com/?foo=bar|baz"
if var escapedURLString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
    NSURL(string: escapedURLString)
}

Returns: http://example.com/?foo=bar%7Cbaz

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