NSURL URLWithString: is null with non-english accented characters

前端 未结 5 1350
孤独总比滥情好
孤独总比滥情好 2020-11-29 01:48

I have the following string...

NSString *googleSearchString = @\"http://www.google.com/search?q=lyrics+%22Tænder+På+Dig%22+%22Jakob+Sveistrup%22\";


        
相关标签:
5条回答
  • 2020-11-29 02:14

    In 2k16 method stringByAddingPercentEscapesUsingEncoding: is deprecated and there is no way escape this correctly. When URL is predefined just use browser encoded string, because stringByAddingPercentEncodingWithAllowedCharacters: method cannot escape whole URL.

    0 讨论(0)
  • 2020-11-29 02:15

    Use this for SWIFT 4:

    let url = myURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    let myURL = URL(string: url)
    
    0 讨论(0)
  • 2020-11-29 02:25

    Using Swift 2.2

    For escaping non-english characters, for example: to make an URL request do:

    let urlPath = path.URLString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

    Here urlPath is an Optional and path is your original url (the one with non-english characters)

    0 讨论(0)
  • 2020-11-29 02:30

    Some times a space in the url can cause this problem .

    0 讨论(0)
  • 2020-11-29 02:33

    You need to escape the special characters to make it work properly. Something like:

    [NSURL URLWithString:[googlSearchString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
    
    0 讨论(0)
提交回复
热议问题