iOS 开发中,经常需要对url编码与解码。

iOS9之前

1.url编码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12

+ (NSString*)encodeUrl:(NSString *)urlString {
    if (0 == urlString.length) {
        return KBlankString;
    }
    
    return (__bridge_transfer NSString*) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)urlString,
                                                                                 NULL,
                                                                                 (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                 kCFStringEncodingUTF8);
}

2.url解码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
+ (NSString *)decodeUrl:(NSString *)urlString {
    
    if (0 == urlString.length) {
        return KBlankString;
    }
    
    return (__bridge_transfer NSString*) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
                                                                                                 (__bridge CFStringRef)urlString,
                                                                                                 CFSTR(""),kCFStringEncodingUTF8);
    
}

iOS7之后

1.url编码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
+ (NSString *)URLEncode:(NSString *)urlString {
    if (0 == urlString.length) {
        return KBlankString;
    }
    return [urlString stringByAddingPercentEncodingWithAllowedCharacters:[self URLEncodeCharSet]];
}

static NSCharacterSet *_sharedCharacterSet = nil;

+ (NSCharacterSet *)URLEncodeCharSet {
    
    if (nil == _sharedCharacterSet) {
        _sharedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"!*'();:@&=+$,/?%#[]"] invertedSet];
    }
    
    return _sharedCharacterSet;
}

2.url解码

1
2
3
4
5
6
7
+ (NSString *)URLDecode:(NSString *)urlString {
    if (0 == urlString.length) {
        return KBlankString;
    }
    
    return [urlString stringByRemovingPercentEncoding];
}