在iOS app开发中,如果需要对url中的中文和特殊字符进行url编码,一般有两种方法:
1.使用NSString方法
encode:
NSString* sURL = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
decode:
NSString* sURL = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
2.使用CFStringRef方法
encode:
指定需要编码的字符
1 NSString* sURL = (NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)input, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);
如果仅仅只需要编码中文
1 NSString* sURL = (NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)input, NULL, NULL, kCFStringEncodingUTF8);
decode:
1 NSMutableString* inputStr = [NSMutableString stringWithString:input]; 2 [inputStr replaceOccurrencesOfString:@"+" 3 withString:@" " 4 options:NSLiteralSearch 5 range:NSMakeRange(0, [inputStr length])]; 6 7 NSString* sURl = [inputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];