你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iPhone開發--使用Obj-C對數據等進行URLEncoding編碼

iPhone開發--使用Obj-C對數據等進行URLEncoding編碼

編輯:IOS開發綜合

在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的專欄
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved