在Objective-c进行网络编程时,经常需要把数据转换成URLEncoding编码,如对+号编码后,变成%2b.这里我们给出一种实现.
//NSString+URLEncoding.h
#import
@interface NSString (URLEncodingAdditions)
- (NSString *)URLEncodedString;
- (NSString *)URLDecodedString;
@end
//NSString+URLEncoding.m
#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
因为是扩展了NSString,使用的时候就比较简单了,首先在使用本类的文件中引入NSString+URLEncoding.h头文件,然后直接用NSString中的URLEncodedString与URLDecodedString方法,如:转载自:http://www.voland.com.cn/urlencoding_for_objective-c