Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString stringByReplacingPercentEscapesUsingEncoding doesn't work

I need to get url string from NSString. I do the following:

   NSString * str = [NSString stringWithString:@"[email protected]"];

    NSString * eStr = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"%@",eStr);

The result is [email protected]. But I need i%40gmail.com. replacing NSUTF8StringEncoding with NSASCIIStringEncoding doesn't help.

like image 737
ArisRS Avatar asked Mar 19 '12 17:03

ArisRS


1 Answers

You're using the wrong method. This does the opposite, translating percent escapes to their characters. You probably want to use stringByAddingPercentEscapesUsingEncoding:.

NSString *str  = @"[email protected]";
NSString *eStr =
    [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Apart from that, looks like the @ character is not escaped by default. Then, as the documentation for the above method points out, you'll need to use CoreFoundation to achieve what you want.

NSString *str  = @"[email protected]";

CFStringRef eStr = CFURLCreateStringByAddingPercentEscapes(
    kCFAllocatorDefault,
    (CFStringRef)str,
    NULL,
    (CFStringRef)@"@",
    kCFStringEncodingUTF8
);

NSLog(@"%@", eStr);

CFRelease(eStr);

Please check the documentation to know more about the function used and how to make it fit your needs.

like image 194
sidyll Avatar answered Sep 21 '22 17:09

sidyll