url中文轉碼

調用接口參數含有中文字符,調用出錯。谷歌百度了半天關於IOS轉碼的,都沒有效果。less

後來在官方文檔找到了解決方法:this

CFURLCreateStringByAddingPercentEscapesurl

Discussion

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 allocatorcharactersToLeaveEscaped, 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

  1. NSString *urlString = @"http://test.com/root?&city=中國";  接口

  2.     //把NSString 轉 CFStringRef  ci

  3.     CFStringRef originalURLString = (__bridge CFStringRef)urlString;  文檔

  4.     CFStringRef preprocessedString =  

  5.     CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, originalURLString, CFSTR(""), kCFStringEncodingUTF8);  

  6.     CFStringRef urlString1 =  

  7.     CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, preprocessedString, NULL, NULL, kCFStringEncodingUTF8);  

  8.     CFURLRef url = CFURLCreateWithString(kCFAllocatorDefault, urlString1, NULL);  

  9.     //CFStringRef 轉 NSString   

  10.     urlString = (__bridge NSString*) url;  

  11.   

  12.     //轉換後,發現並不是NSString 而是NSURL 這很奇怪 因此再轉一次  

  13.     if ([urlString isKindOfClass:[NSURL class]]) {  

  14.         NSURL *url2 = (__bridge NSURL*) url;;  

  15.         urlString = [url2 absoluteString];  

  16.     }  

  17.     NSLog(@"nsstring:%@",urlString);  

大概就這樣。搞定。

相關文章
相關標籤/搜索