iosnsurlfoundationpercent-encoding

NSURLComponents to get percent encoding


According to documentation of NSURLComponents:

If you set the unencoded property, you can then obtain the encoded equivalent by reading the encoded property value and vice versa.

I tried to get the percent encoding versions of the query and path of the url but I miss something:

NSURL * url = [NSURL URLWithString:@"http://google.com"];

NSURLComponents * components = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:YES];
components.query = @"oauth_callback=http://google.com";

NSLog(@"Encoded: %@", [components URL]); 
//-> Encoded: http://google.com?oauth_callback=http://google.com
//Does not encode "/" or ":"

Where do I fail ?


Solution

  • I think NSURLComponent's behaviour is right. From Wikipedia:

    In the "query" component of a URI (the part after a ? character), for example, "/" is still considered a reserved character but it normally has no reserved purpose, unless a particular URI scheme says otherwise. The character does not need to be percent-encoded when it has no reserved purpose.