常用分类—URL的编码与解码

新建NSString的分类,对URL进行编码与解码

@interface NSString (URLEncoding)
- (NSString *)URLEncodedString;
- (NSString *)URLDecodedString;
@end
@implementation NSString (URLEncoding)
/*
CFURLCreateStringByAddingPercentEscapes(<#CFAllocatorRef allocator#>, <#CFStringRef originalString#>, <#CFStringRef charactersToLeaveEscaped#>)—Core Foundation 框架提供的C函数,把内容转为URL编码

<#CFStringRef originalString#> — 制定了将本身为非法URL字符不进行编码的字符集合,例如:"! * ()"等符号

<#CFStringRef charactersToLeaveEscaped#> — 将本身为合法的URL字符需要进行编码的字符集合
*/
- (NSString *)URLEncodedString{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}
- (NSString *)URLDecodedString{
/*
CFURLCreateStringByReplacingPercentEscapes(<#CFAllocatorRef allocator#>, <#CFStringRef originalString#>, <#CFStringRef charactersToLeaveEscaped#>)

<#CFStringRef charactersToLeaveEscaped#> — 指定不进行编码的字符集合
*/
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

你可能感兴趣的:(常用分类—URL的编码与解码)