NSURL is returning nil for a valid URL

我的未来我决定 提交于 2019-12-20 03:11:29

问题


I have a valid URL for google maps , which if you run in your browser would show an image of a map. However, when I put it inside my Swift code and try to create an NSURL from String it returns nil

let urlString = "https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid&center=37.33233141,-122.0312186&path=color:0xff0000|weight:10|37.33233141,-122.0312186|21.422570,%2039.826190&markers=color:blue%7Clabel:S%7C37.33233141,-122.0312186&markers=color:blue%7Clabel:S%7C21.422570,39.826190&zoom=1&size=1080x1920"
let url = NSURL(string: urlString)

Currently , this returns nil, I don't know why. Am I doing something wrong?


回答1:


It should work: Here is why http://www.url-encode-decode.com

        let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)

Since above API is deprecated alternative approach is

    let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)



回答2:


Looking at the Apple documentation:

This method expects URLString to contain only characters that are allowed in a properly formed URL. All other characters must be properly percent escaped. Any percent-escaped characters are interpreted using UTF-8 encoding.

Likely there's something incorrect in your string, and you need to encode it before passing it to NSURL, you can do this via stringByAddingPercentEncodingWithAllowedCharacters:

if let encodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet() {
    url = NSURL(string: urlString)
}


来源:https://stackoverflow.com/questions/34805082/nsurl-is-returning-nil-for-a-valid-url

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