Reputation: 3293
I need to send an NSArray of NSDictionaries as a query parameter in a GET request for NSURLRequest. An example of what I would like to send is this:
[{"name":"John","age":20},{"name":"Bob","age":25}]
I was sending this via AFNetworking with the following:
- (NSString *)makeJSONString {
NSMutableArray *mutableArray = [NSMutableArray array];
for (RDPerson *person in [self.people allValues]) {
NSDictionary *currentPerson = @{@"name" : person.name, @"age" : person.age};
[mutableArray addObject:currentPerson];
}
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mutableArray options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
Now that I have moved my code to NSURLSession, this is not working, so what is the proper way to put this object into a query parameter?
The part that isn't working is
[self.urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
This completion handler is returning null for the data and response
SOLUTION: SO it turns out before you commit this to the URL you have to do this for your url:
[mutableString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
then set this to the URL with URLWithString
Upvotes: 0
Views: 208
Reputation: 10407
WARNING: Your proposed solution is not correct and can potentially cause a security hole, not to mention that it may fail randomly in unpredictable ways, for two reasons:
The stringByAddingPercentEscapesUsingEncoding
is almost invariably the wrong method to call. It is deprecated because it does not work correctly.
If you need to support any version of iOS prior to iOS 9, use CFURLCreateStringByAddingPercentEscapes
.
You should not be encoding an entire URL at once. You should always encode only the actual blob of arbitrary data that you are adding to the URL, e.g.
NSString *JSONBlob = ...
NSString *encodedJSONBlob = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge NSString *)JSONBlob,
NULL,
CFSTR(":/?#[]@!$&'()*+,;="),
kCFStringEncodingUTF8);
NSString *URL = [NSString stringWithFormat:@"http://example.com/.../foo.cgi?myparam=%@&foo=bar", encodedJSONBlob];
Otherwise, the encoding method may double-encode parts of the URL that have already been encoded.
For details, see: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/WorkingwithURLEncoding/WorkingwithURLEncoding.html
And as others have mentioned, if your JSON data is large, you should be sending it in a POST body instead.
Upvotes: 1