After reading all the answers for this topic and the (wrong) accepted one, I want to add my contribution.
IF the target is iOS7+, and in 2017 it should since XCode makes really hard to deliver compatibility under iOS8, the best way, thread safe, fast, amd will full UTF-8 support to do this is:
(Objective C code)
@implementation NSString (NSString_urlencoding)
- (NSString *)urlencode {
static NSMutableCharacterSet *chars = nil;
static dispatch_once_t pred;
if (chars)
return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
// to be thread safe
dispatch_once(&pred, ^{
chars = NSCharacterSet.URLQueryAllowedCharacterSet.mutableCopy;
[chars removeCharactersInString:@"!*'();:@&=+$,/?%#[]"];
});
return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
}
@end
This will extend NSString, will exclude RFC forbidden characters, support UTF-8 characters, and let you use things like:
NSString *myusername = "I'm[evil]&want(to)break!!!$->àéìòù";
NSLog(@"Source: %@ -> Dest: %@", myusername, [myusername urlencode]);
That will print on your debug console:
Source: I'm[evil]&want(to)break!!!$->àéìòù -> Dest: I%27m%5Bevil%5D%26want%28to%29break%21%21%21%24-%3E%C3%A0%C3%A9%C3%AC%C3%B2%C3%B9
... note also the use of dispatch_once to avoid multiple initializations in multithread environments.