NSURL URLWithString: is null with non-english accented characters

隐身守侯 提交于 2019-11-27 00:36:52

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

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

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)

Use this for SWIFT 4:

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

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.

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

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