Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a cURL request (with --data-urlencode) into AFNetworking GET request

This issue might not be related to AFNetworking specifically, but more in constructing an NSURLRequest. I am trying to issue the falling GET request using AFNetworking-

curl -X GET \
  -H "X-Parse-Application-Id: Q82knolRSmsGKKNK13WCvISIReVVoR3yFP3qTF1J" \
  -H "X-Parse-REST-API-Key: iHiN4Hlw835d7aig6vtcTNhPOkNyJpjpvAL2aSoL" \
  -G \
  --data-urlencode 'where={"playerName":"Sean Plott","cheatMode":false}' \
  https://api.parse.com/1/classes/GameScore

This is from the parse.com API https://parse.com/docs/rest#queries-constraints.

However, I can't figure out how to write the

[AFHTTPClient getPath:parameters:success:failure:]

for this request. The where clause does not look like a dictionary, however this function only takes a dictionary for its parameter input.

like image 698
Devang Avatar asked Jul 28 '26 14:07

Devang


1 Answers

The parameter expects an NSDictionary which will be turned into key/value pairs in the URL. So the key is easy but to the value you'll need to convert it to JSON before setting it in the dictionary...

NSDictionary *jsonDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                                @"Sean Plott", @"playerName",
                                [NSNumber numberWithBool:NO], @"cheatMode", nil];

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];

if (!jsonData) {
    NSLog(@"NSJSONSerialization failed %@", error);
}

NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:
                            json, @"where", nil];

If we assume that your client is configured something like this (normally you subclass AFHTTPClient and could move this stuff inside

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://api.parse.com/"]];
[client setDefaultHeader:@"X-Parse-Application-Id" value:@"Q82knolRSmsGKKNK13WCvISIReVVoR3yFP3qTF1J"];
[client setDefaultHeader:@"X-Parse-REST-API-Key" value:@"iHiN4Hlw835d7aig6vtcTNhPOkNyJpjpvAL2aSoL"];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];

Then you should be able to call

[client getPath:@"1/classes/GameScore"
     parameters:parameters 
        success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"Success %@", responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Failed %@", error);
        }];
like image 131
Paul.s Avatar answered Jul 30 '26 03:07

Paul.s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!