1、原始方法:stringByAddingPercentEscapesUsingEncoding: ios(2.0,9.0)
image.png
NSString *data = @"https://baike.baidu.com/item/百度百科/85895?fr=aladdin";
NSString *urlStr = [data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", urlStr);
结果输出:
https://baike.baidu.com/item/%E7%99%BE%E5%BA%A6%E7%99%BE%E7%A7%91/85895?fr=aladdin
2、新方法:stringByAddingPercentEncodingWithAllowedCharacters: ios(7.0)
NSString *data = @"https://baike.baidu.com/item/百度百科/85895?fr=aladdin";
// 以下两句代码处理结果一样:对`#%^{}[]|\"<>空格 这些字符进行编码
NSString *dataUTF8 = [data stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}[]|\"<> "] invertedSet]];
// NSString *dataUTF8 = [data stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSLog(@"%@",dataUTF8);
结果输出:
https://baike.baidu.com/item/%E7%99%BE%E5%BA%A6%E7%99%BE%E7%A7%91/85895?fr=aladdin
NSCharacterSet (NSURLUtilities)
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
但是现在有的URL中包含的#是不需要进行编码的,可以修改代码为:
// 字符集中若哪个字符不需要编码,去掉即可
NSString *dataUTF8 = [data stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"`%^{}[]|\"<> "] invertedSet]];
参考资料:
url出现特殊字符处理
网友评论