views:

852

answers:

2

I'm using ASIHTTPRequest to communicate with the server asynchronously. It works great, but I'm doing requests in different controllers and now duplicated methods are in all those controllers. What is the best way to abstract that code (requests) in a single class, so I can easily re-use the code, so I can keep the controllers more simple. I can put it in a singleton (or in the app delegate), but I don't think that's a good approach. Or maybe make my own protocol for it with delegate callback.

Any advice on a good design approach would be helpful. Thanks.

+4  A: 

I am using subclasses of Ben Copsey's ASIHTTPRequest very heavily for a web service client I hope to finish in the next couple weeks. It's a great project and his work has saved me a great deal of time and effort.

I have an ASINetworkQueue set up in the application delegate. The queue is sent the -go message so that it is ready to receive requests. I add my subclassed requests to this queue. Each request is processed and issues its notifications, and my view controller handles the response data accordingly.

What I have done is subclass ASIHTTPRequest and:

  1. Set up an -init method (or -initWithParams: method, depending on the request)
  2. Override -requestFailed: and -requestCompleted: to handle HTTP error messages coming back from the web service
  3. My view controllers register to observe NSNotification notifications that come from error handling in the -requestCompleted: method

As view controllers are pushed on and popped off the navigation stack, I add and remove different registrations. Some view controllers only need to listen for certain subclassed request types.

Listening for NSNotification allows me to issue UIAlertView dialogs to let the user know something went wrong, or to handle the request response data (feeding results into a Core Data store, for example) when the request yields a successful HTTP error.

Whether the request succeeds or fails, I remember to -release the request when I'm done with it.

Alex Reynolds
A: 

Alex,

You always seem to be the man when I'm searching for networkRequest goodness!! :-)

This seems really interesting what you're doing with NSNotification and your ASIHTTPRequest subclass. Could you go into a little more detail with your controllers and how you listen for those messages (requestCompleted/requestFailed)? Also feeding your results into Core Data Store seems like a killer idea!

soo, if you have the time, enlighten us with your skillz?

salomoko
this should be a comment on Alex's post.
Ross
I don't have an option to comment on his post?
salomoko