一晒奕、背景需求
有時候我們在項目中經常會遇到一個URL字符串轉成NSURL之后為空,或者將URL字符串轉成NSURL之后般哼,請求數據是請求不到的吴汪,這個問題很有可能是URL字符串的編碼解碼問題。其中很常見的是GET請求中拼接字符串的時候其中含有中文蒸眠。
二漾橙、問題解決
這個問題系統(tǒng)已經有API,我們看下系統(tǒng)實現
iOS9之前用的方法
- 編碼
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - 解碼
[urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
其中urlString是我們給定的URL字符串
iOS9之后系統(tǒng)推薦使用
- 編碼
[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]]; - 解碼
[urlString stringByRemovingPercentEncoding];
對于NSCharacterSet有問題的可參考NSCharacter?Set
其中以下是有關于轉換的特殊字符楞卡,我們根據需要選擇合適的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);
以上!=淘捡!