URLPathAllowedCharacterSet 不编码感叹号

URLPathAllowedCharacterSet not encoding exclamation marks

我正在尝试构建一个 url 并确保对路径中的所有特殊字符进行编码,我目前未能这样做,可能是由于误解了 path 属性 NSURLComponents 有效。

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]];

// Returns 带有“!”的 url,未编码

[items addObject:components.URL];

我在 components.path 中做错了什么吗?

提前感谢大家的帮助。

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);
                }
            }
        }
    }

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

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