How to encode or decode URL in objective-c

user4951 picture user4951 · May 31, 2012 · Viewed 8k times · Source

Is there something like

+(NSString *) URLencode: (NSString *) someString


+(NSString *) URLdecode: (NSString *) someString

If so, how to implement it?

Note to downvoters. This is NOT a simple question. I need something that can comprehensively do this. For example:

NSString * test = @"汉字马拉松是";
NSString * encoded = [test stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
PO(encoded);
PO(test);

Will yield the following:

2012-06-04 16:04:22.709 BadgerNew[2266:17003] <0xcd890 GrabClass.m:(930)> encoded (null)
2012-06-04 16:04:22.710 BadgerNew[2266:17003] <0xcd890 GrabClass.m:(931)> test 汉字马拉松是

I want my encoding to be able to URL encode EVERYTHING including japanese language, etc.

So I want encoded to contain something along %E6%B1%89%E5%AD%97%E9%A9%AC%E6%8B%89%E6%9D%BE%E6%98%AF

There are 2 different methods in http://mobiledevelopertips.com/networking/a-better-url-encoding-method.html

None are good enough.

I need to be able to encode ALL strings, including japanese/chinese characters.

Update: I followed H2CO3 answer and do this: NSString * test = @"汉字马拉松是"; NSString * encoded = [test stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; PO(encoded); PO(test); PO(encoded);

Work as expected.

Answer

Leon Lucardie picture Leon Lucardie · May 31, 2012

You probably want to take a look at the stringByAddingPercentEscapesUsingEncoding and stringByReplacingPercentEscapesUsingEncoding methods.

Encoding example (using ASCII):

NSString* encodedString =
[originalString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

Decoding example (using ASCII):

NSString* originalString =
[encodedString stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

EDIT: If this doesn't give the desired results try replacing NSASCIIStringEncoding with NSUTF8StringEncoding.

Also you might want to try the variant of above methods :

NSString * encodedString =
  (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
    (CFStringRef)originalString,
    NULL,
    (CFStringRef)@"!*'();:@&=+$,/?%#[]",
    kCFStringEncodingUTF8 );

Which will work better in some cases