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
));