SWIFT: Why is “NSURL(string:” returning with Nil, even though it's a valid url in a browser?

后端 未结 4 681
旧巷少年郎
旧巷少年郎 2021-01-13 05:02

The first two example links are working the third one returns NIL.

Why is NSUrl returning nil for such string, even though it\'s a valid url in a browser?

Am

相关标签:
4条回答
  • 2021-01-13 05:18

    In iOs 9:

    myString = myString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    

    Hope it helps

    0 讨论(0)
  • 2021-01-13 05:27

    You should URL-encode the URL like this:

    selectedFeedUrl = selectedFeedUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

    0 讨论(0)
  • 2021-01-13 05:35

    For swift3 you can do like this

    let url = URL(string:url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!
    
    0 讨论(0)
  • 2021-01-13 05:35

    Thank you guys for your help. I added these two lines to my code and it works now:

        selectedFeedURL = selectedFeedURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        selectedFeedURL =  selectedFeedURL.stringByReplacingOccurrencesOfString("%09%09", withString:"")
    
    0 讨论(0)
提交回复
热议问题