Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between stringByAddingPercentEscapesUsingEncoding: and stringByReplacingPercentEscapesUsingEncoding:

What is please the difference between the 2 methods stringByAddingPercentEscapesUsingEncoding: and stringByReplacingPercentEscapesUsingEncoding: ?

I have read the NSString Class Reference several times and still haven't got it.

Also, is there please a way to force those methods to encode "+" signs as well?

In my iPhone app I have to urlencode a base64 encoded (i.e. letters, digits, pluses and slashes) avatar and ended up using the CFURLCreateStringByAddingPercentEscapes method instead of the above methods...

- (NSString*)urlencode:(NSString*)str
{
    return (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
        NULL,
        (__bridge CFStringRef) str,
        NULL,
        CFSTR("+/"),
        kCFStringEncodingUTF8));
}
like image 227
Alexander Farber Avatar asked Feb 17 '14 12:02

Alexander Farber


1 Answers

stringByAddingPercentEscapesUsingEncoding will convert the Unicode* character to the percent escape format.

stringByReplacingPercentEscapesUsingEncoding will do the opposite, convert the percent escape to the Unicode*.

*Actually not Unicode, but the encoding you choose.

Examples:

NSString *rawText = @"One Broadway, Cambridge, MA"; 
NSString *encodedText = [rawText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Encoded text: %@", encodedText);
NSString *decodedText = [encodedText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Original text: %@", decodedText);

Here’s the output:

Encoded text: One%20Broadway,%20Cambridge,%20MA

Original text: One Broadway, Cambridge, MA

Disadvantage: stringByAddingPercentEscapesUsingEncoding doesn’t encode reserved characters like ampersand (&) and slash (/)

Workaround:use Foundation function CFURLCreateStringByAddingPercentEscapes instead.

Source: http://cybersam.com/ios-dev/proper-url-percent-encoding-in-ios

like image 100
Guilherme Avatar answered Oct 20 '22 23:10

Guilherme