ios UrlEncode与UrlDecode

url字符串中具有特殊功能的特殊字符的字符串,或者中文字符,作为参数用GET方式传递时,需要用urlencode处理一下。当然,有时作为Post参数传递,也需要urlencode处理一下。

NSString+URL.h

#import 

@interface NSString (URL)
-(NSString*)encodeString:(NSString*)unencodedString;
-(NSString *)decodeString:(NSString*)encodedString;
@end

NSString+URL.m

#import "NSString+URL.h"

@implementation NSString (URL)

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


//URLDEcode
-(NSString *)decodeString:(NSString*)encodedString
{
    NSString *decodedString = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                              (__bridge CFStringRef)encodedString,CFSTR(""),
                               CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

@end

 

你可能感兴趣的:(ios UrlEncode与UrlDecode)