完成最后一个请求时发送下一个请求

时间:2016-04-18 09:35:16

标签: ios nsurlconnection nsurl nsurlrequest afnetworking-3

我有100多个请求。我需要在最后一个请求完成后发送新请求,因此服务器不会返回错误代码 - 429。 如何通过afnetworking 3.0制作这个?

4 个答案:

答案 0 :(得分:0)

我对AFNetworking的具体API不太熟悉,但您可以设置:

  1. 包含所有待处理请求的变量数组
  2. 一个名为(例如)sendNext()的方法,它删除数组的第一个条目,异步执行请求,并在完成块内调用自身。
  3. 当然,您需要一个终止条件,这只是在数组变空时停止。

答案 1 :(得分:0)

有两种方法可以解决您的问题。

首先,创建一个操作队列并将所有请求添加到队列中。之后,创建新请求的操作,然后将依赖项添加到队列中的所有请求。因此,您的新操作(将执行新请求)将在最后一个请求完成后执行。

其次,您可以使用dispatch_barrier_async,它将在并发队列上创建一个同步点。这意味着您应该创建一个并发队列来执行100+请求,并且自定义队列中的dispatch_barrier_async块将执行新请求。

答案 2 :(得分:0)

Thanks Sendoa for the link to the GitHub issue where Mattt explains why this functionality is not working anymore. There is a clear reason why this isn't possible with the new NSURLSession structure; Tasks just aren't operations, so the old way of using dependencies or batches of operations won't work.

I've created this solution using a dispatch_group that makes it possible to batch requests using NSURLSession, here is the (pseudo-)code:

// Create a dispatch group
dispatch_group_t group = dispatch_group_create();

for (int i = 0; i < 10; i++) {
    // Enter the group for each request we create
    dispatch_group_enter(group);

    // Fire the request
    [self GET:@"endpoint.json"
       parameters:nil
          success:^(NSURLSessionDataTask *task, id responseObject) {
                  // Leave the group as soon as the request succeeded
                  dispatch_group_leave(group);
          }
      failure:^(NSURLSessionDataTask *task, NSError *error) {
                  // Leave the group as soon as the request failed
                  dispatch_group_leave(group);
              }];
}

// Here we wait for all the requests to finish
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    // Do whatever you need to do when all requests are finished
});
I want to look write something that makes this easier to do and discuss with Matt if this is something (when implemented nicely) that could be merged into AFNetworking. In my opinion it would be great to do something like this with the library itself. But I have to check when I have some spare time for that.

答案 3 :(得分:0)

此问题可能与AFNetworking 3.0 AFHTTPSessionManager using NSOperation重复。您可以关注@Darji评论进行少量通话,对于100+通话,请添加这些实用程序类https://github.com/robertmryan/AFHTTPSessionOperation/。 同时发送100+请求操作是非常不切实际的方法。如果可能的话尽量减少它。