How to perform a batch of AFNetworking requests that depend on each other

前提是你 提交于 2019-12-12 08:56:10

问题


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:


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



来源:https://stackoverflow.com/questions/11417924/how-to-perform-a-batch-of-afnetworking-requests-that-depend-on-each-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!