iOS 9以前
URL Encode 用的是CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator, CFStringRef originalString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped, CFStringEncoding encoding) 这个方法。
而URL Decode用的是CFStringRef CFURLCreateStringByReplacingPercentEscapesUsingEncoding(CFAllocatorRef allocator, CFStringRef origString, CFStringRef charsToLeaveEscaped, CFStringEncoding encoding)这个方法。
(具体参数的含义有兴趣的可以自己搜搜,因为已经废除了,这里就不深入解释了)
此外还有两个苹果封装在NSString里面的方法
- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc;
- (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc;
使用方法
+ (NSString*)urlEncode:(NSString*)text
{
// 表示!*'();:@&=+$,/?%#[] 这些字符出现在URL里面时 会使用数字字母加%的形式代替
NSString *result = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes
(kCFAllocatorDefault, (CFStringRef)text, NULL, CFSTR("!*'();:@&=+$,/?%#[]"),
kCFStringEncodingUTF8);
return result;
}
+ (NSString*)urlDecode:(NSString*)text
{
NSString *result = (__bridge NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding
(kCFAllocatorDefault, (CFStringRef)text, CFSTR(""), kCFStringEncodingUTF8);
return result;
}
// 编码一般都是UTF-8
- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc;
- (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc;
但是这些方法都在iOS 9以后都被废除了,取而代之的是
- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters;
@property (nullable, readonly, copy) NSString *stringByRemovingPercentEncoding // Decode
使用方法
@implementation NSString (Extension)
// 这里使用分类, self表示原字符串
- (NSString *)urlEncode{
// !*'();:@&=+$,/?%#[]{}" 表示URL里遇到这些字符 将使用字母数字加%的形式代替
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:
@"!*'();:@&=+$,/?%#[]{}\""] invertedSet];
return [self stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
}
- (NSString *)urlDecode{
return [self stringByRemovingPercentEncoding];
}
@end
注意
在CFURLCreateStringByAddingPercentEscapes里面需要替换的字符是@"!*'();:@&=+$,/?%#[]" 但是在stringByAddingPercentEncodingWithAllowedCharacters里面设置同样的字符,两个方法得出来的结果是不一样的。原因是CFURLCreateStringByAddingPercentEscapes默认会处理花括号和双引号{}"这个三个字符。但是stringByAddingPercentEncodingWithAllowedCharacters不会。(曾因为这个问题导致签名失败,坑的我想哭)