saurabh
saurabh

Reputation: 540

Add new AFHTTPRequestOperation with dependency on existing request

Sending few post request using

- (AFHTTPRequestOperation *)POST:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

I want to perform one get request once all of the above request have processed so I have created AFHTTPRequestOperation and adding dependency as

for (AFHTTPRequestOperation *operation in manager.operationQueue.operations ) {        
        [AFHTTPRequestOperationObject addDependency:operation];
    }
    [manager.operationQueue addOperation: AFHTTPRequestOperationObject];

But the operation is performed before the completion of existing post request.

Upvotes: 1

Views: 142

Answers (3)

Aaron Brager
Aaron Brager

Reputation: 66244

You shouldn't use NSOperation dependencies to solve this problem. In your case, later operations rely on processing with completionBlock but NSOperationQueue and AFNetworking both consider that work a side effect.

completionBlock is:

the block to execute after the operation’s main task is completed.

(my emphasis).

In the case of AFHTTPRequestOperation, "the operation’s main task" is "making an HTTP request". The "main task" doesn't include parsing JSON, persisting data, checking HTTP status codes, etc. - that's all handled in completionBlock.

To perform one request after other requests have processed, you'll need to make that request in the completion handler, once you've verified you have all the data you need to proceed.

Upvotes: 1

Gerard
Gerard

Reputation: 699

It appears that AFHTTPRequestOperation(s) complete as soon as the HTTP call is made and returns. The success and failure blocks are called after these operations are complete. So if you have NSOperation A dependent on B which is a AFHTTPRequestOperation then you may see B run, followed by A, followed by B's success block. Seems to work if you create a "finished" operation and make A dependent on it. Then have B enqueue the "finished" operation for running when B calls its success or failure block. The "finished" operation in effect signals A that B has done all you wanted it to do.

Upvotes: 0

Sumit Gera
Sumit Gera

Reputation: 1241

While using OperationQueues, it is not necessary that the responses will be received in the same order as the requests made. You will have to make sure that you make the GETrequest after complete execution of multiple POST requests. This explains the process to perform the operations serially with a completionHandler (which in your case should be the GET request that you want to execute at the completion of the POST requests.)

Upvotes: 0

Related Questions