开发者

NSString method to percent escape '&' for URL

Which NSString encoding method will percent escape the ampersand (&) character correctly into %26?

stringByAddingPercentEscapesUsingEncoding:NSUTF8Strin开发者_StackOverflowgEncoding

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"];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜