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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With