url字符串中具有特殊功能的特殊字符的字符串,或者中文字符,作为参数用GET方式传递时,需要用urlencode处理一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//URLEncode +(NSString*)encodeString:(NSString*)unencodedString{ // CharactersToBeEscaped = @":/?&=;+!@#$()~',*"; // CharactersToLeaveUnescaped = @"[]."; NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)unencodedString, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8)); return encodedString; } //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; } |
iOS之后新的API NS_AVAILABLE(10_9, 7_0)
NSCharacterSet系统内置的一些返回CharacterSet 的方法
1 2 3 4 5 6 |
URLFragmentAllowedCharacterSet "#%<>[\]^`{|} URLHostAllowedCharacterSet "#%/<>?@\^`{|} URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|} URLPathAllowedCharacterSet "#%;<>?[\]^`{|} URLQueryAllowedCharacterSet "#%<>[\]^`{|} URLUserAllowedCharacterSet "#%/:<>?@[\]^` |
使用
1 2 3 4 |
//encode [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; //decode [string stringByRemovingPercentEncoding]; |
当然系统内置的CharacterSet要是满足不了你的话,你可以自定义NSCharacterSet
1 2 |
NSCharacterSet *c = [NSCharacterSet characterSetWithCharactersInString:@"'();:@&=+$,/?%#[]"]; [string stringByAddingPercentEncodingWithAllowedCharacters:c]; |
转载请注明:天狐博客 » iOS中URL字符串的URLencode与URLdecode