Migration issue from AFNetworking 1.3 to AFNetworking 2.0

I am trying to migrate a project from AFNetworking 1.3 to AFNetworking 2.0.

In the AFNetworking 1.3 project, I have this code:

- (void) downloadJson:(id)sender
{

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myServer/api/call?param1=string1&param2=string2"]];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        // handle success

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"%ld", (long)[response statusCode]);

        NSDictionary *data = JSON;
        NSString *errorMsg = [data objectForKey:@"descriptiveErrorMessage"];
        // handle failure

    }];

    [operation start];

}

When a client sends a URL that has not been properly formatted or with bad parameters, the server sends a 400 error back and turns on the JSON with "descriptiveErrorMessage", which I read in the bounce block. I use this "descriptiveErrorMessage" to determine what is wrong with the URL and tell the user if necessary.

The AFNetworking 2.0 project code is as follows:

- (void)downloadJson:(id)sender
{
 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myServer/api/call?param1=string1&param2=string2"]];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        // handle success

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        // any way to get the JSON on a 400 error?

    }];

    [operation start];
}

AFNetworking 2.0 JSON "descriptiveErrorMessage" , . NSHTTPURLResponse , , , , - .

JSON ? ?

.

+4
2

, responseData operation .

, JSON, , .

, .

+4

. "AFHTTPRequestOperationManager"

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager GET:@"http://localhost:3005/jsondata" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"Result: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"Error: %@", [error localizedDescription]);
}];
+1

All Articles