Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking 2.0 - use responseObject as NSDictionary

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

this is the recommended way to send GET request in AFNetworking 2.0. I want to get the value of a specific key in the json, so I want to use responseObject as NSDictionary. this is what I was trying:

NSError *jsonError = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:kNilOptions error:&jsonError];

it didn't work:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary bytes]: unrecognized selector sent to instance 0xa048120'

how can I get the value of a specific key in responseObject?

like image 858
Brian Avatar asked Sep 30 '13 04:09

Brian


2 Answers

By default, AFHTTPRequestOperationManager sets responseSerializer to an AFJSONResponseSerializer instance, so responseObject already is your parsed JSON (in your case, it'll be an NSDictionary according to what you said).

Then, just use it as you'd use a dictionary:

NSString *value = responseObject[@"someKey"];
like image 69
Marcelo Fabri Avatar answered Nov 16 '22 03:11

Marcelo Fabri


The response object is already a dictionary! AFNetworking did handle that for you.

like image 5
vikingosegundo Avatar answered Nov 16 '22 04:11

vikingosegundo