2013-06-24 156 views
1

我正在与AFNetworking从网上获取一些JSON。我如何获得返回的异步请求的响应?这里是我的代码:等待AFJSONRequestOperation完成

- (id) descargarEncuestasParaCliente:(NSString *)id_client{ 

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://whatever.com/api/&id_cliente=%@", id_client]]]; 

     __block id RESPONSE; 

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

      RESPONSE = JSON; 

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

     [operation start]; 

     return RESPONSE; 
    } 

回答

3

我觉得你对块的工作方式感到困惑。

这是一个异步请求,因此您无法返回在完成块内计算出的任何值,因为您的方法在执行时已经返回。

你必须改变你的设计,要么从成功块内执行回调,要么传递你自己的块,并让它调用。

举个例子

- (void)descargarEncuestasParaCliente:(NSString *)id_client success:(void (^)(id JSON))success failure:(void (^)(NSError *error))failure { 

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://whatever.com/api/&id_cliente=%@", id_client]]]; 

    __block id RESPONSE; 

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

     if (success) { 
      success(JSON); 
     } 

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
     NSLog(@"ERROR: %@", error); 
     if (failure) { 
      failure(error); 
     } 
    }]; 

    [operation start]; 
} 

你会再调用这个方法就像如下

[self descargarEncuestasParaCliente:clientId success:^(id JSON) { 
    // Use JSON 
} failure:^(NSError *error) { 
    // Handle error 
}]; 
+0

感谢您的示例代码!但是,在这种情况下,函数的返回类型是否会变为void? –

+0

你绝对正确 –

+0

我是这么想的。你的实现确实有效。非常感谢! :) –