Reputation: 935
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?
Upvotes: 3
Views: 8100
Reputation: 27354
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]];
Upvotes: 4