10

How to do URL encoding in NSURL ?

Thanks

mipadi
  • 380,288
  • 84
  • 512
  • 473
Biranchi
  • 15,670
  • 23
  • 121
  • 160
  • It is easier now with iOS 7: http://stackoverflow.com/questions/3423545/objective-c-iphone-percent-encode-a-string/20271177#20271177 – Steve Moser Nov 04 '15 at 16:58

3 Answers3

27

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
  • 57,797
  • 21
  • 121
  • 142
6

stringByAddingPercentEscapesUsingEncoding: has some problems with URL arguments.

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

amrox
  • 6,157
  • 2
  • 35
  • 57
3

This worked for me:

NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:[url  stringByAddingPercentEscapesUsingEncoding:STRING_ENCODING_IN_THE_SERVER]] 
                                                      encoding:STRING_ENCODING_IN_THE_SERVER 
                                                         error:&error];
Jorge Perez
  • 1,596
  • 1
  • 12
  • 4