iOS开发中Objective-C 对 URL的URLEncode(编码)与URLDecode(解码)

版权归Aaidong所有〜转载需声名〜  欢迎大家访问:http://blog.csdn.net/aaidong

废话不多说,直接上代码。

//
//  NSString+URL.h
//
//  Created by aidong on 15/5/8.
//  Copyright (c) 2015年 aidong. All rights reserved.
//

/**
 *  url字符串中具有特殊功能的特殊字符的字符串,或者中文字符,作为参数用GET方式传递时,需要用urlencode处理一下。
 *
 *  例如:在 iOS 程序访问 HTTP 资源时,像拼出来的 http://unmi.cc?p1=%+&sd f&p2=中文,其中的中文、特殊符号&%和空格都必须进行转译才能正确访问。
 */

/**
 *  调用示例:
        引入头文件:NSString+URL.h
 
        // URLEncode
        NSString *unencodedString = @"cc?p1=%+&sd f&p";
        NSString *encodedString = [unencodedString URLEncodedString];
 
        // URLDecode
        NSString *undecodedString = @"%25+&sd%20&p2=%E4%B8%AD%E6%96%87";
        NSString *decodedString = [undecodedString URLDecodedString];
 */

#import 

@interface NSString (URL)

/**
 *  URLEncode
 */
- (NSString *)URLEncodedString;

/**
 *  URLDecode
 */
-(NSString *)URLDecodedString;

@end

 
  
//
//  NSString+URL.m
//
//  Created by aidong on 15/5/8.
//  Copyright (c) 2015年 aidong. All rights reserved.
//

#import "NSString+URL.h"

@implementation NSString (URL)

/**
 *  URLEncode
 */
- (NSString *)URLEncodedString
{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *unencodedString = self;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

/**
 *  URLDecode
 */
-(NSString *)URLDecodedString
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *encodedString = self;
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

@end


你可能感兴趣的:(objective-c,工具)