Search code examples
iosobjective-curl-encoding

URLPathAllowedCharacterSet not encoding exclamation marks


I'm trying to build a url and make sure that all the special characters in the path get encoded, I'm currently failing to do so, possibly due to misunderstanding of how the path property of NSURLComponents works.

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

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

// I thought that stringByAddingPercentEncodingWithAllowedCharacters would encode characters like "!" into "%21"

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

// Returns a url with "!", unencoded

[items addObject:components.URL];

Am I doing something fundamentally wrong in components.path?

Thanks everyone for your help in advance.


Solution

  • Since URLPathAllowedCharacterSet contains "!", you would need to create a new character set by creating a mutable copy of the URLPathAllowedCharacterSet and removing the "!":

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