在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];
摘自 zcl369369的專欄