Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString URL decode?

I have tried a lot of approaches out there, but this tiny little string just cannot be URL decoded.

NSString *decoded;
NSString *encoded = @"fields=ID%2CdeviceToken";
decoded = (__bridge NSString*)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)encoded, NULL, NSUTF8StringEncoding);
NSLog(@"decodedString %@", decoded);

The code above just logs the same (!) string after replacing percent escapes.

Is there a reliable solution out there? I think some kind of RegEx solution based on some documentation could work. Any suggestion?

like image 732
Geri Borbás Avatar asked Mar 27 '13 03:03

Geri Borbás


2 Answers

Another option would be:

NSString *decoded = [encoded stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
like image 146
rmaddy Avatar answered Sep 19 '22 17:09

rmaddy


Use CFSTR("") instead of NULL for the second to last argument. From the CFURL reference:

charactersToLeaveEscaped

Characters whose percent escape sequences, such as %20 for a space character, you want to leave intact. Pass NULL to specify that no percent escapes be replaced, or the empty string (CFSTR("")) to specify that all be replaced.

    NSString *encoded = @"fields=ID%2CdeviceToken";
    NSString *decoded = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)encoded, CFSTR(""), kCFStringEncodingUTF8);
    NSLog(@"decodedString %@", decoded);

Prints:

2013-03-26 21:48:52.559 URLDecoding[28794:303] decodedString fields=ID‭,‬deviceToken

like image 39
Carl Veazey Avatar answered Sep 20 '22 17:09

Carl Veazey