0

我有一种情况,我需要向服务器发出多个请求,而后续请求将取决于先前的请求

1) request 1
2) process data
3) request 2 based on data in step 2
4) process data

AFNetworking 2 的最佳方法是什么

4

2 回答 2

1

在第一个请求的完成处理程序中调用第二个请求。这是一些示例代码:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON Response 1: %@", responseObject);

    // Process data here, and use it to set parameters or change the url for request2 below

    [manager GET:@"http://example.com/request2.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSLog(@"JSON Response 2: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"Error 2: %@", error);
    }];
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error 1: %@", error);
}];
于 2013-11-08T00:53:31.040 回答
0

我玩了一下,最终实现了我自己的完成块和失败块,因此它们可以通过向 AFHTTPRequestOperation 类添加一个类别作为请求操作在某个线程上执行

- (void)startAndWaitWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [self start];
    [super waitUntilFinished];

    id responseObject = self.responseObject; // need this line for AFNetworking to create error;

    if (self.error) {
        if (failure) failure(self, self.error);
    } else {
        if (success) success(self, responseObject);
    }
}

操作将开始,然后阻塞线程,直到操作完成。然后根据成功或失败,在完成操作之前调用相应的块。

这样我可以一个接一个地链接多个请求操作,完成块将具有来自前一个请求完成块的处理数据

于 2014-08-31T23:35:32.603 回答