-1

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

4

4 回答 4

0

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

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

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

于 2016-04-18T09:44:50.563 回答
0

我对 的特定 API 不是很熟悉AFNetworking,但您可以设置:

  1. 一个包含所有待处理请求的变量数组,
  2. 一个名为(例如)的方法sendNext(),它删除数组的第一个条目,异步执行请求,并在完成块内调用自身。

当然,您将需要一个终止条件,即当数组为空时停止。

于 2016-04-18T09:42:06.093 回答
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.
于 2016-04-18T09:49:57.910 回答
0

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

于 2016-04-28T17:44:29.067 回答