不幸的是,您需要比 Apple 提供的更聪明:
stringByAddingPercentEscapesUsingEncoding:
这将转义所有无效的 URL 字符,使有效的“http://foo.com/hey%20dude/”变成“http://foo.com/hey%2520dud/”,这不是我们想要的.
根据苹果文档:http: //developer.apple.com/library/mac/documentation/CoreFOundation/Reference/CFURLRef/Reference/reference.html#//apple_ref/c/func/CFURLCreateStringByAddingPercentEscapes
我创建了一个 NSURL 类别,它可以做正确的事情并使用奇怪的字符串,例如带有部分编码的字符串(即“http://foo.com/hey dude/i%20do%20it/”)。
这是代码:
@interface NSURL (SmartEncoding)
+ (NSURL *)smartURLWithString:(NSString *)str;
@end
@implementation NSURL (SmartEncoding)
+ (NSURL *)smartURLWithString:(NSString *)str
{
CFStringRef preprocessed = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)str, CFSTR(""), kCFStringEncodingUTF8);
if (!preprocessed)
preprocessed = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)str, CFSTR(""), kCFStringEncodingASCII);
if (!preprocessed)
return [NSURL URLWithString:str];
CFStringRef sanitized = CFURLCreateStringByAddingPercentEscapes(NULL, preprocessed, NULL, NULL, kCFStringEncodingUTF8);
CFRelease(preprocessed);
NSURL *result = (NSURL*)CFURLCreateWithString(NULL, sanitized, NULL);
CFRelease(sanitized);
return [result autorelease];
}
@end
它适用于 UTF8 字符串编码和 ASCII 字符串。