AFHTTPRequestOperation同步请求

时间:2013-11-07 22:56:18

标签: ios afnetworking-2

我遇到的情况是我需要向服务器发出多个请求,后续请求将取决于之前的请求

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

AFNetworking 2的最佳解决方法是什么

2 个答案:

答案 0 :(得分: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);
}];

答案 1 :(得分: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);
    }
}

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

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