iOS字符串中特殊字符的编码与解码

1.网络请求时url中携带@等特殊字符的解决方案
a.对url进行特殊字符编码
- ( nullable  NSString *)stringByAddingPercentEncodingWithAllowedCharacters:( NSCharacterSet *)allowedCharacters NS_AVAILABLE ( 10 _9, 7 _0);
b.对url进行特殊字符解码
@property ( nullable , readonly , copy ) NSString *stringByRemovingPercentEncoding NS_AVAILABLE ( 10 _9, 7 _0);
____SAMPLE____
[ @"!*'();:@&=+ $,/?%#[]" stringByAddingPercentEncodingWithAllowedCharacters :[ NSCharacterSet URLFragmentAllowedCharacterSet ]];  //编码
[ @"!*'();:@&=+ $,/?%#[] 编码后的字符串 " stringByRemovingPercentEncoding ];  //解码
几种编码策略
/ /返回一个包含字符的字符集允许在一个URL的用户子组件。
+(NSCharacterSet *)URLUserAllowedCharacterSet NS_AVAILABLE(10 _9 7 _0);

/ /返回一个包含字符的字符集允许在一个URL的密码子组件。
+(NSCharacterSet *)URLPasswordAllowedCharacterSet NS_AVAILABLE(10 _9 7 _0);

/ /返回一个包含字符的字符集允许URL的子组件。
+(NSCharacterSet *)URLHostAllowedCharacterSet NS_AVAILABLE(10 _9 7 _0);

/ /返回一个包含字符的字符集允许URL的路径组件。字符“;”是一种合法的路径,但是建议最好是percent-encoded兼容NSURL(-stringByAddingPercentEncodingWithAllowedCharacters:percent-encode任何‘;’字符如果你通过URLPathAllowedCharacterSet)。
+(NSCharacterSet *)URLPathAllowedCharacterSet NS_AVAILABLE(10 _9 7 _0);

/ /返回一个包含字符的字符集允许一个URL的查询组件。
+(NSCharacterSet *)URLQueryAllowedCharacterSet NS_AVAILABLE(10 _9 7 _0);

/ /返回一个包含字符的字符集允许URL的片段组件。
+(NSCharacterSet *)URLFragmentAllowedCharacterSet NS_AVAILABLE(10 _9 7 _0);

编码字符范围
URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

PS:想要执行对非特殊字符做同样的转码(例如’&’ , ’,’ , ‘.’等),请换用如下函数(但是已经在iOS9之后弃用了)
NSString *encodeStr = ( NSString *) CFBridgingRelease ( CFURLCreateStringByAddingPercentEscapes ( kCFAllocatorDefault , ( CFStringRef )originString, NULL , ( CFStringRef ) @"!*'();:@&=+ $,./?%#[]" , kCFStringEncodingUTF8 ));
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值