如何执行彼此依赖的一批AFNetworking请求 [英] How to perform a batch of AFNetworking requests that depend on each other
问题描述
我需要执行一系列服务器调用,这些服务器调用顺序运行,并且只有在所有先前请求都成功之后才能执行一个请求。
所以,我的想法是为每个请求创建一个 AFHTTPRequestOperation
,并使用 [myAFHTTPClient enqueueBatchOfHTTPRequestOperations:]
将其触发。
我可以通过调用
[myAFHTTPClient.operationQueue setMaxConcurrentOperationCount:1]
但是我如何确保其余的操作仅在先前的操作成功后才能运行?
我尝试创建对于每个调用 [myAFHTTPClient cancelAllOperations]
的操作,如果该操作失败,则为 completionBlock
队列中的请求同时运行,因此下一个请求在取消之前可能已经发送到服务器。我应该怎么办?
由于 AFHTTPRequestOperations
只是标准的 NSOperations
,编写了一个示例项目,并弄清楚了如何解决此问题:
如果 NSOperationQueue
的 maxConcurrentOperationCount
设置为1, NSOperation
的 completionBlock
和队列中的下一个 NSOperation
同时运行。
但是,如果每个 NSOperation
通过调用 addDependency:
链接到其先前的操作,操作的执行一直等到上一个操作的 completionBlock
已经完成。
因此,将所有 NSOperations
链接在一起通过 addDependency:
并在操作失败的情况下,取消当前操作的完成块中的其余操作。
(另请参见 NSOperations及其完成块是否同时运行?)
I need to perform a series of server calls that run sequentially and where one request can only be executed if all previous requests have been successful.
So, my idea was to create an AFHTTPRequestOperation
for each request and use [myAFHTTPClient enqueueBatchOfHTTPRequestOperations:]
to fire them off.
I can make them run sequentially by calling
[myAFHTTPClient.operationQueue setMaxConcurrentOperationCount:1]
But how can I make sure that the remaining operations run only if the previous operations were successfull?
I tried to create a completionBlock
for every operation that calls [myAFHTTPClient cancelAllOperations]
in case the operation failed, but the completionBlock and the next operation in the queue run concurrently, so the next request could already be sent to the server before it gets cancelled. What should I do?
Since AFHTTPRequestOperations
are just standard NSOperations
, wrote a sample project and figured out how to solve this problem:
If the NSOperationQueue
's maxConcurrentOperationCount
is set to 1, an NSOperation
's completionBlock
and the next NSOperation
in the queue run simultaneously.
But, if every NSOperation
is linked to its previous operation by calling addDependency:
, the execution of an operation waits until the previous operation's completionBlock
has finished.
So, link all NSOperations
together via addDependency:
and in case an operation failes, cancel the remaining operations in the completion block of the current operation.
(see also Do NSOperations and their completionBlocks run concurrently?)
这篇关于如何执行彼此依赖的一批AFNetworking请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!