NSURL 为有效的 URL 返回 nil
NSURL is returning nil for a valid URL
我有 google 地图的有效 URL,如果您在浏览器中 运行 会显示地图图像。但是,当我将它放入我的 Swift 代码中并尝试从 String 创建一个 NSURL 时,它 returns nil
let urlString = "https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid¢er=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)
目前,这个 returns 没有,我不知道为什么。我做错了什么吗?
它应该有效:这就是为什么 http://www.url-encode-decode.com
let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
由于上面的 API 已弃用,替代方法是
let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
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.
您的字符串中可能存在错误,您需要在将其传递给 NSURL
之前对其进行编码,您可以通过 stringByAddingPercentEncodingWithAllowedCharacters
:
进行此操作
if let encodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet() {
url = NSURL(string: urlString)
}
我有 google 地图的有效 URL,如果您在浏览器中 运行 会显示地图图像。但是,当我将它放入我的 Swift 代码中并尝试从 String 创建一个 NSURL 时,它 returns nil
let urlString = "https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid¢er=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)
目前,这个 returns 没有,我不知道为什么。我做错了什么吗?
它应该有效:这就是为什么 http://www.url-encode-decode.com
let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
由于上面的 API 已弃用,替代方法是
let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
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.
您的字符串中可能存在错误,您需要在将其传递给 NSURL
之前对其进行编码,您可以通过 stringByAddingPercentEncodingWithAllowedCharacters
:
if let encodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet() {
url = NSURL(string: urlString)
}