10

How to do URL encoding in NSURL ?

Thanks

mipadi
  • 398,885
  • 90
  • 523
  • 479
Biranchi
  • 16,120
  • 23
  • 124
  • 161
  • 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
  • 58,763
  • 21
  • 123
  • 144
6

stringByAddingPercentEscapesUsingEncoding: has some problems with URL arguments.

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

amrox
  • 6,207
  • 3
  • 36
  • 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,606
  • 1
  • 13
  • 4