Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURL URLWithString: is null with non-english accented characters

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?

like image 827
regulus6633 Avatar asked Jan 23 '10 23:01

regulus6633


2 Answers

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

[NSURL URLWithString:[googlSearchString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]; 
like image 56
clee Avatar answered Sep 23 '22 22:09

clee


Use this for SWIFT 4:

let url = myURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) let myURL = URL(string: url) 
like image 31
Yaroslav Dukal Avatar answered Sep 25 '22 22:09

Yaroslav Dukal