2016-04-18 39 views

回答

0

我不是很熟悉的AFNetworking特定的API,但你可以設置:

  1. 包含您的所有未決請求變量數組,
  2. 調用的方法(例如)sendNext(),消除了數組的第一個入口,異步執行請求,並在完成塊內調用自身。

當然,你將需要一個終止條件,而這只是當數組變爲空時停止。

+0

thx.這是解決我的代碼中的問題的方法。我正在通過網絡連接尋找更好的方法。 – lsdoy

+0

如果它具有某種批次/隊列功能,那將會很棒。我沒有使用過這個框架。 –

0

有兩種方法可以處理您的問題。

首先,創建一個操作隊列並將所有請求添加到隊列中。之後,創建新請求的操作,然後將依賴項添加到隊列中的所有請求。因此,您的新操作(將執行新請求)將在最後一次請求完成後執行。其次,你可以使用dispatch_barrier_async,它會在你的併發隊列中創建一個同步點。這意味着您應該創建一個併發隊列來執行您的100+請求,並且您的自定義隊列中的dispatch_barrier_async塊將執行新的請求。

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. 
相關問題