ios中URL字符串的URLencode与URLdecode

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


//URLEncode

  +(NSString*)encodeString:(NSString*)unencodedString{

    if([[[UIDevicecurrentDevice]systemVersion]floatValue] >=9.0) {

            return[unencodedString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];

}

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

returnencodedString;
}

//URLDEcode

-(NSString *)decodeString:(NSString*)encodedString

{

//NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];

NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,

(__bridge CFStringRef)encodedString,

CFSTR(""),

CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

return decodedString;


有用户反馈,说iOS9之后,CFURLCreateStringByAddingPercentEscapes这个方法废弃,所以根据官方的描述 替换使用stringByAddingPercentEncodingWithAllowedCharacters 这个方法。


stringByAddingPercentEncodingWithAllowedCharacters 需要传递参数NSCharacterSet

你可能感兴趣的:(ios中URL字符串的URLencode与URLdecode)