tags:

views:

334

answers:

2

Hi ,

How to do URL encoding in NSURL ?

Thanks

+6  A: 

You can use stringByAddingPercentEscapesUsingEncoding:

NSString* escapedUrlString =
   [unescapedString stringByAddingPercentEscapesUsingEncoding:
                        NSUTF8StringEncoding];

However, in my experience, this method isn't quite perfect (in handling some reserved characters), and in many cases I needed to use the variant:

 NSString * escapedUrlString =
  (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
    (CFStringRef)unescapedString,
    NULL,
    (CFStringRef)@"!*'();:@&=+$,/?%#[]",
    kCFStringEncodingUTF8 );
notnoop
+1, but with a reminder that `CFURLCreateStringByAddingPercentEscapes` returns a string with a +1 retain count, so you must `release` it when you're done.
Dave DeLong
+2  A: 

stringByAddingPercentEscapesUsingEncoding: has some problems with URL arguments.

In conjunction I use gtm_stringByEscapingForURLArgument from Google Toolbox for Mac for URL arguments.

amrox