NSURL is returning nil for a valid URL

前端 未结 2 1086
一整个雨季
一整个雨季 2021-01-22 03:19

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 S

相关标签:
2条回答
  • 2021-01-22 03:49

    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)
    }
    
    0 讨论(0)
  • 2021-01-22 03:53

    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())!)
    
    0 讨论(0)
提交回复
热议问题