问题
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!?!
回答1:
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.
回答2:
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;
}
回答3:
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"];
}
来源:https://stackoverflow.com/questions/2159341/nsstring-method-to-percent-escape-for-url