NSURL URLWithString: is null with non-english accented characters

99封情书 提交于 2019-11-26 17:27:52

问题


I have the following string...

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

Notice that it has some accented characters. When I try to turn that into a url the returned url is null...

[NSURL URLWithString:googleSearchString];

So normally the url works except when there are accented non-english characters in the string. Any help on how to handle that?


回答1:


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

[NSURL URLWithString:[googlSearchString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];



回答2:


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)




回答3:


Use this for SWIFT 4:

let url = myURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let myURL = URL(string: url)



回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/2125230/nsurl-urlwithstring-is-null-with-non-english-accented-characters

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