What is the difference between stringByAddingPercentEscapesUsingEncoding: and stringByReplacingPercentEscapesUsingEncoding:

StackOverflow https://stackoverflow.com/questions/21829489

質問

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));
}
役に立ちましたか?

解決

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top