Talha Ch Talha Ch - 4 months ago 20
Objective-C Question

How to perform AFHTTPRequestOperation in AFNetworking 2

I've implemented the JSON parsing using

AFNetworking
many time in some previous apps as:

NSString *string = [NSString stringWithFormat:@"%@?get_all_data", BaseURLString];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
//performing parsing here

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//error message displayed here
}


But as of today I started working on an app after a while I came to use
AFNetworking
again and I installed in using
pods
so as I write this same code as I use to write before it gives me the error saying
Unknown Receiver AFHTTPRequestOperation. Do you mean AFHTTPRequestSerializer?


After searching about it I found that it's
AFNetworking 2
or
3
era now and they have somehow changed the scenerio. I didn't find the exact solution on how to implement it now. So can anyone write the code in the answer below that works with the latest version of
AFNetworking
.

Answer

This is the new approach of AFNetworking 3.x to parse data:

NSString *path = @"yourapilink";
NSString *escapedPath = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

[manager GET:escapedPath  parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Hope it help !