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