URL编码是一种常见的编码方式,作用不多说,直接上代码。
- URL编码:
- (NSString *)URLEncodedString {
// CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
// CharactersToLeaveUnescaped = @"[].";
NSString *unencodedString = self;
NSString *encodedString = (NSString *)
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
return encodedString;
}
-
URL解码:
- (NSString *)URLDecodedString {
NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
return [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
建议这两个方法放在NSString的分类中,并且声明为实例方法,这样可以直接用NSString的对象去调用。
- 调用示例
NSString * string = @"zhansan啦啦啦啦1234567";
NSString * urlEncode = [string URLEncodedString];
NSString * urlDecode = [string URLDecodedString];
NSLog(@"urlEncode == %@",urlEncode);
NSLog(@"urlDecode == %@",urlDecode);
- 打印结果:
urlEncode == zhansan%E5%95%A6%E5%95%A6%E5%95%A6%E5%95%A61234567
urlDecode == zhansan啦啦啦啦1234567