Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can AFNetworking handle a queue of requests?

My example on iOS 6:

  • 10 Multi-Part requests need to be sent (in order) to the server. (so the request forms a queue)
  • progress should be shown.
  • if one request fails all following should fail
  • a request queue should be cancellable

Can AFNetworking help me with this? Or should I try to build something with NSOperations and run the loops myself?

If I need to pass context data between theses requests for example a transaction id produced by the first request. Are there any considerations about thread visibility I need to consider?

like image 733
jack Avatar asked Oct 21 '22 13:10

jack


1 Answers

AFNetworking can do this. I recommend that you use AFHTTPRequestOperationManager (which itself uses NSOperation), rather than AFHTTPSessionManager. There are ways to do it with AFHTTPSessionManager, but none as elegant as with operations.

Under the hood, here's what you'd do without the manager:

You will use a request serializer to make your NSMutableURLRequest (for example, [AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:]; there's a similar JSON request serializer too).

Once you have a URL Request, make the operation with [AFHTTPRequestOperation -initWithRequest:]. You should also set its completion blocks.

Finally, add your operation to [AFHTTPRequestOperationManager manager].operationQueue and start it.


Now that you understand how this is basically all working together, here's a simpler approach:

  • Subclass AFHTTPRequestOperationManager, optionally setting the requestSerializer if you don't like the default
  • Override (or copy with new implementation) -POST:parameters:constructingBodyWithBlock:success:failure:] - what you want to do is NOT start your operation right away.
  • Set the NSOperation dependency chains
  • start the first one
like image 87
Aaron Brager Avatar answered Oct 23 '22 09:10

Aaron Brager