NSURL URLWithString: is null with non-english accented characters

CocoaSpecial CharactersNsurl

Cocoa Problem Overview


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?

Cocoa Solutions


Solution 1 - Cocoa

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

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

Solution 2 - Cocoa

Use this for SWIFT 4:

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

Solution 3 - Cocoa

> 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)

Solution 4 - Cocoa

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.

Solution 5 - Cocoa

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionregulus6633View Question on Stackoverflow
Solution 1 - CocoacleeView Answer on Stackoverflow
Solution 2 - CocoaYaroslav DukalView Answer on Stackoverflow
Solution 3 - CocoaHugo AlonsoView Answer on Stackoverflow
Solution 4 - CocoaTimur BernikovichView Answer on Stackoverflow
Solution 5 - CocoaMartin JacobView Answer on Stackoverflow