iosobjective-cafnetworkingafhttprequestoperation

How to handle empty responseObject in AFHTTPRequestOperation


I have a problem handling an empty responseObject in the AFHTTPRequestOperation during the GET request. I'm using the AFNetworking Library.

If the content of the responsteObject is "0 objects" my application crashes when I'm trying to access keys which aren't available in the responseObject. How can I handle that gracefully? Here is how my code looks like:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:requestURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSLog(responseObject[@"NotAvailableKey"];
    }    
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

If the content of the responseObject is not "0 objects" the code works perfectly. Even if I'm trying to access a key which is not in the responseObject.


Solution

  • Your code crashes because responseObject sometimes in not an NSDictionary. And so it not responds to objectForKey:. You should check what is a class of responseObject:

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:requestURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]
        {
             NSLog(responseObject[@"NotAvailableKey"]);
        }
        else
        {
             NSLog(@"Incorrect responseObject");
        }
    }    
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];