Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape URL quesrystring

I make a request to an external API using GET method. For some reasons, the results which I get do not work if the searchText contains spaces e.g. it works fine for stackoverflow, but if searchText is entered as "stack overflow", it will not work (Assume both the values are present). Do I need to escape before making the URL request?

NSString *urlstr = [[NSString alloc] initWithFormat:@"http://mysite.com/xyz?nameBeginsWith=%@", searchText];
like image 444
copenndthagen Avatar asked Feb 21 '11 19:02

copenndthagen


1 Answers

The method stringByAddingPercentEscapesUsingEncoding is now deprecated.

The correct way to escape urls is:

NSString * escapedSearchText = [searchText stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

NSString * url = [NSString stringWithFormat:@"http://example.com/xyz?nameBeginsWith=%@", escapedSearchText];

like image 77
Yusef Maali Avatar answered Oct 28 '22 16:10

Yusef Maali