Encoding the special charecters of a NSString in Objective-c

NSString *unescaped = @"http://www";
NSString *escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
   (CFStringRef)unescaped,
    NULL,
    CFSTR("!*'();:@&=+$,/?%#[]"),
    kCFStringEncodingUTF8);

NSLog(@"escapedString: %@",escapedString);

NSLog output:

escapedString: http%3A%2F%2Fwww

Under ARC one alternative is:

NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
    NULL,
   (__bridge CFStringRef) unescaped,
    NULL,
    CFSTR("!*'();:@&=+$,/?%#[]"),
    kCFStringEncodingUTF8));
Advertisements

One thought on “Encoding the special charecters of a NSString in Objective-c

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s