残念ながら、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
私は、正しいことを行い、部分的なエンコーディングを使用するような奇妙な文字列(つまり、「http://foo.com/hey dude / i%20do%20it /」)で機能するNSURLカテゴリを作成しました。
コードは次のとおりです。
@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のもので正常に動作します。