如何在AFHTTPRequestOperation中处理空的responseObject

时间:2014-05-09 16:50:44

标签: ios objective-c afnetworking afhttprequestoperation

在GET请求期间,我在responseObject处理空AFHTTPRequestOperation时遇到问题。我正在使用AFNetworking Library。

如果responsteObject的内容是“0个对象”,当我尝试访问responseObject中不可用的密钥时,我的应用程序崩溃了。我怎样才能优雅地处理它?以下是我的代码的样子:

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);
    }];

如果responseObject的内容不是“0对象”,则代码可以正常工作。即使我正在尝试访问不在responseObject中的密钥。

4 个答案:

答案 0 :(得分:1)

使用带有[responseObject count]

的条件
    if ([responseObject count] == 0) {
        //do nothing
        return;
    }

答案 1 :(得分:1)

您的代码崩溃,因为responseObject有时不在NSDictionary中。所以它不响应objectForKey:。你应该检查什么是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);
    }];

答案 2 :(得分:0)

在尝试访问键值之前,您可能希望确保响应对象是字典。它可能作为一个数组返回,它会像“非键值编码”异常一样崩溃。

答案 3 :(得分:0)

您可以尝试以下操作:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:requestURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
  if ([responseObject respondsToSelector:@selector:(objectForKey:)]) {
     // Access the key you need to here.
     NSLog(responseObject[@"NotAvailableKey"];
  } else {

   // responseObject is unexpected. Handle the error case here.
  }

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