NSCharacterSet URLHostAllowedCharacterSet doesn't replace '+' sign?

风流意气都作罢 提交于 2019-12-03 11:15:57
zaph

Swift version here.

To escape character use stringByAddingPercentEncodingWithAllowedCharacters:

NSString *URLEscapedString =
[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

The following are useful character sets, actually the characters not included in the sets:

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

Or create your own characterset with just the characters that you need to escape.

NSCharacterSet *customCharacterset = [[NSCharacterSet characterSetWithCharactersInString:@"your characters"] invertedSet];

Creating a characterset combining all of the above:

NSCharacterSet *URLFullCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@" \"#%/:<>?@[\\]^`{|}"] invertedSet];

Creating a Base64

In the case of Base64 characterset:

NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"/+=\n"] invertedSet];

Note: stringByAddingPercentEncodingWithAllowedCharacters will also encode UTF-8 characters requiring encoding.

Example to verify the characters in the set:

void characterInSet(NSCharacterSet *set) {
    NSMutableString *characters = [NSMutableString new];
    NSCharacterSet *invertedSet = set.invertedSet;
    for (int i=32; i<127; i++) {
        if ([invertedSet characterIsMember:(unichar)i]) {
            NSString *c = [[NSString alloc] initWithBytes:&i length:1 encoding:NSUTF8StringEncoding];
            [characters appendString:c];
        }
    }
    printf("characters not in set: '%s'\n", [characters UTF8String]);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!