iOS 含有 中文的URL 转码问题

非ARC模式下:

- (NSString *)encodeToPercentEscapeString: (NSString *) input
{
    NSString *outputStr = (NSString *) 
    CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (CFStringRef)input,
                                            NULL,
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8);
    return outputStr;
}

- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];

    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

 

ARC模式下:

- (NSString *)encodeToPercentEscapeString: (NSString *) input
{
    NSString*  outputStr = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                                                        NULL, /* allocator */
                                                                                        (__bridge CFStringRef)input,
                                                                                        NULL, /*解决含有的转义字符*/
                                                                                        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                        kCFStringEncodingUTF8);
    return outputStr;
}
- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                withString:@""
                options:NSLiteralSearch
                range:NSMakeRange(0,
                [outputStr length])];

    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

 

posted @ 2015-12-10 10:03  Ficow  阅读(675)  评论(0编辑  收藏  举报