在Objective-c進行網絡編程時,經常需要把數據轉換成URLEncoding編碼,如對+號編碼後,變成%2b.這裡我們給出一種實現.
[cpp] <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.h
#import
@interface NSString (URLEncodingAdditions)
- (NSString *)URLEncodedString;
- (NSString *)URLDecodedString;
@end</span>
[cpp] <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>
<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];