0

In my current iOS app, I need to perform several network operation when the app becomes active (I'd rather get everything at once than to query things when user click on dedicated tab). I'm using a UIViewController that should be displayed when the app goes to the foreground and handle all network stuff in it.
Is that the recommended way to do it ?

The requests I need to issue are something like:

request1
   if result1
      request2
         request3
   else if result2
      request4
         request3

In order to avoid spaghetti code, is there a lib to use that enable chained requests like those ones? I'm using ASIHttpRequest and I did not find any nice way to perform that (even with queue).

Luc
  • 16,604
  • 34
  • 121
  • 183

2 Answers2

2

Nothing wrong with that, assuming your UIViewController is some sort of "loading". Perhaps a better way to handle it would be to create a NSObject subclass, and have that handle your network operations, so in the ApplicationDidBecomeActive: you can just fire that off, and still have the sure carrying on with your app.

Amit Shah
  • 4,176
  • 2
  • 22
  • 26
  • you mean a singleton object that would handle the network operation logic (should they need to be also called from somewhere else in the code) ? That's a good idea though. – Luc Feb 07 '12 at 15:13
  • Yeah, you could use a singleton to achieve it. – Amit Shah Feb 07 '12 at 15:56
2

AFNetworking 0.9 added the ability to batch requests. AFHTTPCLient -enqueueBatchOfHTTPRequestOperationsWithRequests:progressBlock:completionBlock: enqueues a set of operations; when each operation finishes it fires its own completionBlock like normal, as well as the progress block, which tells you how many of the requests have finished. Then, once all are finished, the final completion block executes.

So in your case, it could be as simple as:

[someClient enqueueBatchOfHTTPRequestOperationsWithRequests:[NSArray arrayWithObjects:request1, request2, request3, request4, nil] progressBlock:nil completionBlock:(controller logic here)];

mattt
  • 19,544
  • 7
  • 73
  • 84
  • I tried AFNetworking not long ago but I was kind of embarassed as it did not make it easy to change the timeout interval, I think this was the reason why I stuck to ASIHttpRequest. I might give AFNetworking another go then. – Luc Feb 07 '12 at 16:16
  • Changing the timeout interval is as simple as setting the property on `NSMutableURLRequest`. Besides, [your timeout interval isn't necessarily guaranteed to be observed](http://stackoverflow.com/questions/1466389/nsmutableurlrequest-timeout-interval-not-taken-into-consideration-for-post-reque). ...which is to say I hope you're finding AFNetworking more palatable this time around :) – mattt Feb 08 '12 at 00:34