0
votes

I need to build a NSURL containing an array in the query segment. Array notation looks like this:

test.com?arr[a]=1&arr[b]=2

The problem here is that NSURL escapes the brackets so the final query segment looks like this:

test.com?arr%5Ba%5D=1&arr%5Bb%5D=2

After some research i stumbled upon the NSURLComponents class but just like i already expected, NSURLQueryItem objects can only take NSStrings as value and thus not create the wanted output either. I could not find a way to build a NSURL object containing unescaped brackets yet.

3
[NSURL URLWithString:@"test.com?arr[a]=1&arr[b]=2"] seems to work just fine - mag_zbc
I don't think so. When i call [NSURL URLWithString:@"test.com?arr[a]=1&arr[b]=2"] i get a NSURL object with escaped brackets. - dedda1994
In my personal opinion that's misuse of the query pattern. - vadian
no, actually it's not. This is the de facto http standard to put (assoc.) arrays in the query part of a get request. - dedda1994

3 Answers

0
votes

Add the character you want to keep to theSet

NSString *myString = @"http://foo.bar/?key[]=value";
NSCharacterSet *theSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!*():/?[]="];
NSURL *myUrl = [NSURL URLWithString:[myString stringByAddingPercentEncodingWithAllowedCharacters:theSet]];

I'm not sure if this work, if I move mouse on myUrl to preview it show []
but if I do po myurl.absoluteString it show escape

0
votes

This question is not relevant anymore. As far as i can say, it is not possible to build NSURL objects containing unescaped brackets. If anyone still finds a way to do this, feel free to leave it here.

0
votes

This is an old question, but it hasn't been answered so here goes:

NSArray *queryItems = @[
    [NSURLQueryItem queryItemWithName:@"arr[a]" value:@"1"],
    [NSURLQueryItem queryItemWithName:@"arr[b]" value:@"2"],
];
[components setQueryItems:queryItems];