NSURL is returning nil for a valid URL

邮差的信 提交于 2019-12-02 01:04:18

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())!)

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