【问题标题】:AFHTTPRequestOperation synchronous requestAFHTTPRequestOperation 同步请求
【发布时间】:2013-11-07 22:56:18
【问题描述】:

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

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

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

【问题讨论】:

标签: ios afnetworking-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);
}];

【讨论】:

  • 我想到了,它是最初的实现,但问题是不仅有 2 个链接请求,还有 8 个,有些请求取决于以前的调用,我必须链接7 完成块来调用另一个操作,我有点想有一个更优雅的解决方案。要么就是这样,要么将 AFNetworking 包装在并发的 NSOperation 中
  • 啊,非常不同的问题。您可能不需要求助于 NSOperation,是否可以将 GET 调用包装在一个函数中并将您的数据作为参数之一传递?
  • 大卫,你是什么意思?你的意思是像在完成块中调用下一个请求?
【解决方案2】:

我玩了一会,最终实现了我自己的完成块和失败块,这样它们就可以通过向 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);
    }
}

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 2023-04-01
    相关资源
    最近更新 更多