一、背景需求
有時(shí)候我們?cè)陧?xiàng)目中經(jīng)常會(huì)遇到一個(gè)URL字符串轉(zhuǎn)成NSURL之后為空,或者將URL字符串轉(zhuǎn)成NSURL之后,請(qǐng)求數(shù)據(jù)是請(qǐng)求不到的,這個(gè)問(wèn)題很有可能是URL字符串的編碼解碼問(wèn)題。其中很常見(jiàn)的是GET請(qǐng)求中拼接字符串的時(shí)候其中含有中文。
二、問(wèn)題解決
這個(gè)問(wèn)題系統(tǒng)已經(jīng)有API,我們看下系統(tǒng)實(shí)現(xiàn)
iOS9之前用的方法
- 編碼
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - 解碼
[urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
其中urlString是我們給定的URL字符串
iOS9之后系統(tǒng)推薦使用
- 編碼
[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]]; - 解碼
[urlString stringByRemovingPercentEncoding];
對(duì)于NSCharacterSet有問(wèn)題的可參考NSCharacter?Set
其中以下是有關(guān)于轉(zhuǎn)換的特殊字符,我們根據(jù)需要選擇合適的AllowedCharacterSet
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
三、使用效果
NSString *urlString3 = @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1493299941944&di=76092dbeceb09618622fd7993510c9fb&imgtype=0&src=http%3A%2F%2Fmvimg1.meitudata.com%2F55e2b8683d7464031.jpg";
NSString *url = [urlString3 stringByRemovingPercentEncoding];
NSLog(@"%@",url);
以上?。?!