views:

188

answers:

1

I have a method (getAllTeams:) that initiates an HTTP request using the ASIHTTPRequest library.

NSURL *httpURL = [[[NSURL alloc] initWithString:@"/api/teams" relativeToURL:webServiceURL] autorelease];

ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:httpURL] autorelease];
[request setDelegate:self];
[request startAsynchronous];

What I'd like to be able to do is call [WebService getAllTeams] and have it return the results in an NSArray. At the moment, getAllTeams doesn't return anything because the HTTP response is evaluated in the requestFinished: method.

Ideally I'd want to be able to call [WebService getAllTeams], wait for the response, and dump it into an NSArray. I don't want to create properties because this is disposable class (meaning it doesn't store any values, just retrieves values), and multiple methods are going to be using the same requestFinished (all of them returning an array).

I've read up a bit on delegates, and NSNotifications, but I'm not sure if either of them are the best approach. I found this snippet about implementing callbacks by passing a selector as a parameter, but it didn't pan out (since requestFinished fires independently).

Any suggestions? I'd appreciate even just to be pointed in the right direction.

NSArray *teams = [[WebService alloc] getAllTeams]; (currently doesn't work, because getAllTeams doesn't return anything, but requestFinished does. I want to get the result of requestFinished and pass it back to getAllTeams:)

A: 

Send a reference to the originating class instance along with the call:

[WebService getAllTeams:self];

Then modify -getAllTeams to accept a reference to the originating instance:

- (void) getAllTeams:(id)sender {
    // ...
    [request setDelegate:sender];
    // ...
}

Your originating instance will be responsible for handling the response and cleaning up memory.

Alex Reynolds
Do I get access to responseString / responseData using this method, or is that something I need to handle myself?
Intelekshual
Your delegate methods (which are in your originating class instance) get access to the `responseString` and `responseData`, because those methods are passed a reference to `request`.
Alex Reynolds
Can you use asynchronous calls using this method? I've been messing around with it and haven't been able to get it to work. Just trying to figure out what's going on. Thanks for your help thus far.
Intelekshual
Yes, definitely. Instead of `[request startAsynchronous]` however, I create an instance of `ASINetworkQueue` in my application delegate, and add any `request` instances to this queue. The queue will process them in the order they are added: first-in, first-out. `ASINetworkQueue` is part of `ASIHTTPRequest` -- read the web site documentation to learn how to set this up.
Alex Reynolds