url进行转义
转义
iOS9之前使用 CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator, CFStringRef originalString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped, CFStringEncoding encoding)这个方法
参数解释
allocator 表示为返回字符串的申请的内存,一般为null或kCFAllocatorDefault
originalString 表示需要转义的字符串
charactersToLeaveUnescaped 表示需要保留哪些字符不需要转义
legalURLCharactersToBeEscaped 表示需要转义的字符
encoding 表示需要转义的风格
ios 9之后使用 - (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters 方法
allowedCharacters 系统给了六种默认的风格
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
这些只是对`#%^{}[]|\"<> 加空格共14个字符编码,不包括”&?”等符号,如果想要对“&?”进行编码就需要自己定义编码方式
例如:
NSCharacterSet *customAllowedSet = [[NSCharacterSet characterSetWithCharactersInString:@"!#$%&'()*+,/:;=?@[]"] invertedSet];
具体使用:
+ (NSString*)encodeString:(NSString*)unencodedString {
if([[[UIDevice currentDevice]systemVersion]floatValue] >=9.0) {
NSCharacterSet *customAllowedSet = [[NSCharacterSet characterSetWithCharactersInString:@"!#$%&'()*+,/:;=?@[]"] invertedSet];
NSString *encodeUrl = [unencodedString stringByAddingPercentEncodingWithAllowedCharacters:customAllowedSet];
return encodeUrl;
}
NSString*encodedString = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)unencodedString,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
return encodedString;
}