在Objective-c进行网络编程时,经常需要把数据转换成URLEncoding编码,如对+号编码后,变成%2b.这里我们给出一种实现. span style = "font-family:SimSun;font-size:13px;color:#330033;" //NSString+URLEncoding.h #impo
在Objective-c进行网络编程时,经常需要把数据转换成URLEncoding编码,如对+号编码后,变成%2b.这里我们给出一种实现.
<span style="font-family:SimSun;font-size:13px;color:#330033;">//NSString+URLEncoding.h#import
@interface NSString (URLEncodingAdditions)
- (NSString *)URLEncodedString;
- (NSString *)URLDecodedString;
@end</span>
<span style="font-family:SimSun;font-size:13px;color:#330033;">//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</span>
因为是扩展了NSString,使用的时候就比较简单了,首先在使用本类的文件中引入NSString+URLEncoding.h头文件,然后直接用NSString中的URLEncodedString与URLDecodedString方法,如:
NSString *urlToken = [token URLEncodedString]; 【本文由:湖北阿里云代理商 http://www.558idc.com/aliyun.html提供,感恩】