URLPathAllowedCharacterSet不编码感叹号

时间:2017-04-13 20:48:47

标签: ios objective-c url-encoding

我正在尝试构建一个url并确保路径中的所有特殊字符都被编码,我当前没有这样做,可能是由于误解了path NSURLComponents属性的原因1}}工作。

NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];

NSURLQueryItem *queryItem = [NSURLQueryItem queryItemWithName: @"queryName" value: @"queryValue"];
components.queryItems = @[queryItem];

//我认为stringByAddingPercentEncodingWithAllowedCharacters会编码像“!”这样的字符进入“%21”

components.path = [components.path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];

//返回带有“!”的网址,未编码

[items addObject:components.URL];

我在components.path做了一些根本错误的事情吗?

提前感谢大家的帮助。

2 个答案:

答案 0 :(得分:1)

URLPathAllowedCharacterSet包含“!”,因此不会被编码

您可以使用此例程

枚举此集
    NSCharacterSet *set = [NSCharacterSet URLPathAllowedCharacterSet];

    for (int plane = 0; plane <= 16; plane++) {
        if ([set hasMemberInPlane:plane]) {
            UTF32Char c;
            for (c = plane << 16; c < (plane+1) << 16; c++) {
                if ([set longCharacterIsMember:c]) {
                    UTF32Char c1 = OSSwapHostToLittleInt32(c); // To make it byte-order safe
                    NSString *s = [[NSString alloc] initWithBytes:&c1 length:4 encoding:NSUTF32LittleEndianStringEncoding];
                    NSLog(@"%@", s);
                }
            }
        }
    }

答案 1 :(得分:1)

由于URLPathAllowedCharacterSet包含“!”,您需要通过创建URLPathAllowedCharacterSet的可变副本并删除“!”来创建新的字符集:

NSMutableCharacterSet *characterSet = [[NSCharacterSet URLPathAllowedCharacterSet] mutableCopy];
[characterSet removeCharactersInString:@"!"];