Andreas Eriksson
Andreas Eriksson

Reputation: 9027

StringByAddingPercentEscapes not working on ampersands, question marks etc

I'm sending a request from my iphone-application, where some of the arguments are text that the user can enter into textboxes. Therefore, I need to HTML-encode them.

Here's the problem I'm running into:

NSLog(@"%@", testText); // Test & ?
testText = [testText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", testText); // Test%20&%20?

As you can see, only the spaces are encoded, making the server disregard everything past the ampersand for the argument.

Is this the advertised behaviour of stringByAddingPercentEscapes? Do I have to manually replace every special character with corresponding hex code?

Thankful for any contributions.

Upvotes: 1

Views: 552

Answers (1)

Jilouc
Jilouc

Reputation: 12714

They are not encoded because they are valid URL characters.
The documentation for stringByAddingPercentEscapesUsingEncoding: says

See CFURLCreateStringByAddingPercentEscapes for more complex transformations.

I encode my query string parameters using the following method (added to a NSString category)

- (NSString *)urlEncodedString {
    CFStringRef buffer = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                 (CFStringRef)self,
                                                                 NULL,
                                                                 CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                 kCFStringEncodingUTF8);
    NSString *result = [NSString stringWithString:(NSString *)buffer];
    CFRelease(buffer);

    return result;
}

Upvotes: 1

Related Questions