Replacement for AFJSONRequestOperation in AFNetworking 2.x

James Dunn picture James Dunn · Jan 22, 2014 · Viewed 12.2k times · Source

I am making a basic iPhone app with HTML Requests, by following this tutorial.

The tutorial has me using AFJSONRequestOperation in AFNetworking. The trouble is, I'm using AFNetworking version 2, which no longer has AFJSONRequestOperation.

So, of course, this code (from about half-way down the tutorial, under the heading "Querying the iTunes Store Search API") doesn't compile:

NSURL *url = [[NSURL alloc]
    initWithString:
    @"http://itunes.apple.com/search?term=harry&country=us&entity=movie"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"%@", JSON);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
        NSError *error, id JSON) {
            NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];
[operation start];

My question is, what do I replace AFJSONRequestOperation with so that I can keep working with AFNetworking 2.x? I've googled this and found that no one else seems to be asking this question.

Answer

aahrens picture aahrens · Jan 22, 2014

Could you use AFHTTPSessionManger? So something like

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager GET:[url absoluteString]
  parameters:nil
     success:^(NSURLSessionDataTask *task, id responseObject) {
         NSLog(@"JSON: %@", responseObject);
     }
     failure:^(NSURLSessionDataTask *task, NSError *error) {
        // Handle failure
     }];

Another alternative could be to use AFHTTPRequestOperation and again set the responseSerializer to [AFJSONResponseSerializer serializer]. So something like

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] 
                                            initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation
                                                        , id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Handle error
}];