美文网首页
iOS 9.0之后 URL 编码方法替换

iOS 9.0之后 URL 编码方法替换

作者: C_JH | 来源:发表于2018-04-12 17:20 被阅读136次

最近在做网络请求的时候使用stringByAddingPercentEscapesUsingEncoding:将中文转UTF8发现报警告了。XCode提示如下:

⚠️'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.

很明显,iOS 9.0后stringByAddingPercentEscapesUsingEncoding:方法被弃用了,苹果提示我们使用stringByAddingPercentEncodingWithAllowedCharacters:替换它。该方法将转成UTF8格式,接受一个NSCharacterSet *类型参数,集合里面的char将被忽略。
常用的NSCharacterSet *对象如下:

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

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

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

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

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

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

这里我们使用URLQueryAllowedCharacterSet,即用

// [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

//替换为
[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

搞定嘿嘿。

相关文章

网友评论

      本文标题:iOS 9.0之后 URL 编码方法替换

      本文链接:https://www.haomeiwen.com/subject/iddfkftx.html