iOS 9 以上字符串编码处理

有的时候咱们会碰见字符串里有一些特殊字符在转成URL的时候 会出现转换不了的情况,这个时候需要对字符串进行编码
9.0以前使用stringByAddingPercentEscapesUsingEncoding
9.0之后使用stringByAddingPercentEncodingWithAllowedCharacters
官方文档这样写的
- (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.");

以下是转码demo:

 NSString *resourcePath = @"http://www.baidu.com?tickets=[{\"num\":\"1\",\"priceId\":\"8a82824756\"}]";                               
 NSString *encodePath ;
if (!IOS7_OR_LATER) {
    encodePath = [resourcePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}else{
    encodePath = [resourcePath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容