How to perform a batch of AFNetworking requests th

2019-04-12 00:00发布

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?

1条回答
Deceive 欺骗
2楼-- · 2019-04-12 00:37

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?)

查看更多
登录 后发表回答