有的时候咱们会碰见字符串里有一些特殊字符在转成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];
}