原文地址:http://www.xuebuyuan.com/2039420.html
CFURLCreateStringByAddingPercentEscapes
在作項目的的時候,一般都要用到網絡搜索,所以鏈接(也就是NSURL)也會總是存在一些中文或者特殊字符,但是對於網址是不允許存在一些特殊字符的,所以在這里我列出一個對一個字符串進行NSUTF-8轉碼的宏,希望可以給大家提供方便。
If you have tried to send any information using a GET web request, you would have come cross an annoying problem, That annoying problem is making sure that the URL is corrently encoded.
The issue is that by default most of these methods leave characters such as & = ? within a URL, as they are strictly speaking valid. The problem is that these characters have special meanings in a GET request, and will more than likely make your request invalid.
也就是說, URL 字符串 里面可能包含某些字符,比如‘$‘ ‘&’ ‘?’...等,這些字符在 URL 語法中是具有特殊語法含義的,
比如 URL :http://www.baidu.com/s?wd=%BD%AA%C3%C8%D1%BF&rsv_bp=0&rsv_spt=3&inputT=3512
中 的 & 起到分割作用 等等,如果 你提供的URL 本身就含有 這些字符,就需要把這些字符 轉化為 “%+ASCII” 形式,以免造成沖突。
這就引入:CFURLCreateStringByAddingPercentEscapes 函數。
該函數將 將要添加到URL的字符串進行特殊處理,如果這些字符串含有 &, ? 這些特殊字符,用“%+ASCII” 代替之。
CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(CFStringRef)parameter,
NULL,
CFSTR(":/?#[]@!$&’()*+,;="), // 確定 parameter 字符串中含有:/?#[]@!$&’()*+,;=這些字符時候,這些字符需要被轉化,以免與語法沖突。
kCFStringEncodingUTF8
);
#define NSUTF8String(v) ((NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)(v), NULL, CFSTR(":/?#[]@!$’()*+,;"), kCFStringEncodingUTF8)) 這里記得調用這個宏之后要對獲得的字符串進行一次release