Can AFNetworking handle a queue of requests?

筅森魡賤 提交于 2019-12-07 05:45:15

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/22088186/can-afnetworking-handle-a-queue-of-requests

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