Ios – Why [NSURL URLWithString:] escapes some characters in url string and doesn’t for other characters

iosiphonensurl

I found that [NSURL URLWithString:] method escapes some characters in url string passed to it automatically. e.g. it escapes brackets. But url string contains other non-legal url characters such as < and > causes the method return nil

[[NSURL URLWithString:@"http://foo.bar/?key[]=value[]"] absoluteString]

returns the same result with

[@"http://foo.bar/?key[]=value[]" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

while,

[NSURL URLWithString:@"http://foo.bar/?key[]=value[]<>"] returns nil, not a url with an escaped string.

what exactly happens during initiating NSURL instance? why it escapes (maybe) only brackets?

Best Answer

NSUrl URLWithString: will not escape the string as stated by the docs:

This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8

However, you should be able to do the following using stringByAddingPercentEscapesUsingEncoding::

NSString *myString = @"http://foo.bar/?key[]=value[]<>";
NSURL *myUrl = [NSURL URLWithString:[myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Related Topic