Which NSString encoding method will percent escape the ampersand (&) character correctly into %26
?
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
gets the spaces (%20) and other baddies but ignores ampersands!?!
Ampersands won't be processed by that method because they're legal characters in a URL. You should probably pre-process particularly problematic pieces, piecemeal, prior to this call.
Here is a nice solution to this problem taken from Bagonca blog to url-encode your NSStrings :
+ (NSString *)urlEncodeValue:(NSString *)str
{
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);
return [result autorelease];
}
Add CFBridgingRelease(
for ARC compatibility.
+ (NSString *)urlEncodeValue:(NSString *)str
{
NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8));
return result;
}
The accepted answer isn't quite right I don't think, you need to process the string after calling addPercentEscapesAndReplaceAmpersand
+ (NSString *) addPercentEscapesAndReplaceAmpersand: (NSString *) stringToEncode
{
NSString *encodedString = [stringToEncode stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
return [encodedString stringByReplacingOccurrencesOfString: @"&" withString: @"%26"];
}
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