調用接口參數含有中文字符,調用出錯。谷歌百度了半天關於IOS轉碼的,都沒有效果。less
後來在官方文檔找到了解決方法:this
CFURLCreateStringByAddingPercentEscapesurl
The characters escaped are all characters that are not legal URL characters (based on RFC 3986), plus any characters inlegalURLCharactersToBeEscaped, less any characters in charactersToLeaveUnescaped. To simply correct any non-URL characters in an otherwise correct URL string, pass NULL
for the allocator, charactersToLeaveEscaped, and legalURLCharactersToBeEscaped parameters, and kCFStringEncodingUTF8
as the encoding parameter.spa
It may be difficult to use this function to "clean up" unescaped or partially escaped URL strings where sequences are unpredictable and you cannot specify charactersToLeaveUnescaped. Instead, you can "pre-process" a URL string using CFURLCreateStringByReplacingPercentEscapesUsingEncodingthen add the escape characters using CFURLCreateStringByAddingPercentEscapes, as shown in the following code fragment..net
CFStringRef originalURLString = CFSTR("http://online.store.com/storefront/?request=get-document&doi=10.1175%2F1520-0426(2005)014%3C1157:DODADSS%3E2.0.CO%3B2"); |
CFStringRef preprocessedString = |
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, originalURLString, CFSTR(""), kCFStringEncodingUTF8); |
CFStringRef urlString = |
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, preprocessedString, NULL, NULL, kCFStringEncodingUTF8); |
url = CFURLCreateWithString(kCFAllocatorDefault, urlString, NULL); |
英文我不是很懂,不過憑着直覺就是它了。拿過來處理一下:code
[plain] view plaincopyblog
NSString *urlString = @"http://test.com/root?&city=中國"; 接口
//把NSString 轉 CFStringRef ci
CFStringRef originalURLString = (__bridge CFStringRef)urlString; 文檔
CFStringRef preprocessedString =
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, originalURLString, CFSTR(""), kCFStringEncodingUTF8);
CFStringRef urlString1 =
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, preprocessedString, NULL, NULL, kCFStringEncodingUTF8);
CFURLRef url = CFURLCreateWithString(kCFAllocatorDefault, urlString1, NULL);
//CFStringRef 轉 NSString
urlString = (__bridge NSString*) url;
//轉換後,發現並不是NSString 而是NSURL 這很奇怪 因此再轉一次
if ([urlString isKindOfClass:[NSURL class]]) {
NSURL *url2 = (__bridge NSURL*) url;;
urlString = [url2 absoluteString];
}
NSLog(@"nsstring:%@",urlString);
大概就這樣。搞定。