iOS 9.0之后NSString encode方法替換

在iOS 9.0之后,以前常用的NSString編碼的方法stringByAddingPercentEscapesUsingEncoding:被棄用了,項目中可能會出現(xiàn)一堆如下??:

'stringByAddingPercentEscapesUsingEncoding:' is deprecated: first deprecated in iOS 9.0 - Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.

作為一個有強(qiáng)迫癥的優(yōu)秀程序猿,表示不能忍!

文檔里面是這么說的:

- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc 
NS_DEPRECATED(10_0, 10_11, 2_0, 9_0, "Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, 
which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.");

很明白,用stringByAddingPercentEncodingWithAllowedCharacters:方法替換之。

這個方法官方文檔是這么說的:

// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.

最后一句Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.,意思就是說,任何非7-bit ASCII字符擱到allowedCharacters里面也將被忽略,也就是allowedCharacters里面的字符跟7-bit ASCII字符不會被編碼。

換句話說,上面方法在處理的時候會編碼url的中的非7-bit ASCII字符,如這些【`#%^{}"[]|\<>】,如果需要忽略之,需要通過(NSCharacterSet *)allowedCharacters這個參數(shù)指定??偨Y(jié)如下

[aString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//等價于
[aString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "]];

注意:

  1. 字符集最后是一個空格!
  2. 這里字符集的意思就是,字符串中含有字符集里面的字符將不會被編碼。

另外,URL中常用的NSCharacterSet類型定義在分類NSCharacterSet (NSURLUtilities)中,包含字符集如下:

URLHostAllowedCharacterSet      "#%/<>?@\^`{|}

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}

URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}

URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}

URLQueryAllowedCharacterSet     "#%<>[\]^`{|}

URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

以上,還在等什么,全局搜索替換吧,消滅??!

喜歡我的可以關(guān)注收藏我的個人博客:RobberJJ

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容