Question

I'm making a call to an API, and sometimes my query params contain an ampersand. For instance the parameter might be name=Billy & Bob.

When I create the url, I use:

NSString *url = [NSString stringWithFormat:@"%@/search/%@?name=%@&page=%d", [Statics baseURL], user_id, [term urlEncodeUsingEncoding:NSUTF8StringEncoding], page];
NSURL *fullURL = [NSURL URLWithString:[url stringWithAccessToken]];

I encode the url with this method:

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                               (CFStringRef)self,
                                                               NULL,
                                                               (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                               CFStringConvertNSStringEncodingToEncoding(encoding)));
}

The issue is, the ampersand gets properly encoded via the urlEncodeUsingEncoding method, then the URLWithString method encodes the string again and replaces the % signs created in the string with %25.

Anyone know how to encode query params that contain ampersands?

Was it helpful?

Solution

I found the solution, and it was with NSURLComponents - at this point a completely undocumented class added in iOS7.

NSURLComponents *components = [NSURLComponents new];
components.scheme = @"http";
components.host = @"myurl.com";
components.path = [NSString stringWithFormat:@"%@/mypath/%@", @"/mobile_dev/api", user_id];
components.percentEncodedQuery = [NSString stringWithFormat:@"name=%@", [term urlEncodeUsingEncoding:NSUTF8StringEncoding]];

NSURL *fullURL = [components URL];

By using components.percentEncodedQuery, the term element uses the encoding I put on it, and apple doesn't touch it.

Hopefully this helps someone else.

OTHER TIPS

I use something like this:

- (NSString *)URLEncodedStringWithSourceString:(NSString *)sourceString
{
    NSMutableString *output = [NSMutableString string];
    const unsigned char *source = (const unsigned char *)[sourceString UTF8String];
    int sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || 
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top