在Objective-c进行网络编程时,经常需要把数据转换成URLEncoding编码,如对+号编码后,变成%2b.这里我们给出一种实现.
- #import
- @interface NSString (URLEncodingAdditions)
- - (NSString *)URLEncodedString;
- - (NSString *)URLDecodedString;
- @end</span>
- #import "NSString+URLEncoding.h"
- @implementation NSString (OAURLEncodingAdditions)
- - (NSString *)URLEncodedString
- {
- NSString *result = (NSString *)
- CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
- (CFStringRef)self,
- NULL,
- CFSTR("!*'();:@&=+$,/?%#[] "),
- kCFStringEncodingUTF8);
- [result autorelease];
- return result;
- }
- - (NSString*)URLDecodedString
- {
- NSString *result = (NSString *)
- CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
- (CFStringRef)self,
- CFSTR(""),
- kCFStringEncodingUTF8);
- [result autorelease];
- return result;
- }
- @end</span>
因为是扩展了NSString,使用的时候就比较简单了,首先在使用本类的文件中引入NSString+URLEncoding.h头文件,然后直接用NSString中的URLEncodedString与URLDecodedString方法,如:
NSString *urlToken = [token URLEncodedString];如何联系我:【万里虎】www.bravetiger.cn 【QQ】3396726884 (咨询问题100元起,帮助解决问题500元起) 【博客】http://www.cnblogs.com/kenshinobiy/