不幸的是,你需要比什麼更聰明由蘋果公司提供:
stringByAddingPercentEscapesUsingEncoding:
這將轉義所有無效的URL字符,以便「http://foo.com/hey%20dude/」,這是有效的,成爲「http://foo.com/嘿%2520dud /「,這不是我們想要的。
根據蘋果文檔:http://developer.apple.com/library/mac/documentation/CoreFOundation/Reference/CFURLRef/Reference/reference.html#//apple_ref/c/func/CFURLCreateStringByAddingPercentEscapes
我由NSURL類別,它做正確的事,並與奇數串作品如具有部分編碼的人(即「http://foo.com/hey哥們/ 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的。