views:

92

answers:

2

I am writing a simple library using ASIHTTPRequest where I am fetching URLs in an async manner. My problem is that the main function that I have written to test my lib exits before the async calls are finished.

I am very new to Obj C and iPhone development, can anyone suggest a good way to wait before all the requests are finished in the main function?

Currently, my main function looks like this -

int main(int argc, char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  IBGApp *ibgapp = [[IBGApp alloc] init];
  IBGLib *ibgl = [[IBGLib alloc] initWithUsername:@"joe" andPassword:@"xxx"];

  // The two method calls below download URLs async.
  [ibgl downloadURL:@"http://yahoo.com/" withRequestDelegate:ibgapp andRequestSelector:@selector(logData:)];
  [ibgl downloadURL:@"http://google.com/" withRequestDelegate:ibgapp andRequestSelector:@selector(logData:)];

  [pool release];
  return 0; // I reach here before the async calls are done.
}

So what is the best way to wait till the async calls are done? I tried putting sleep, but obviously doesn't work.

+1  A: 

The simple and dirty solution is to add a loop before [pool release]; line. Sth. like this:

while(1){
    if ([ibgl requests_finished]){
        break;
    }
}

Of course you will need to add requests_finished boolean to IBGLib class and make it true (YES) when the downloads are finished. Remember to handle failure in the request :).

Jacek
+1  A: 

You can also tell the ASIHTTPRequest object to perform those requests synchronously.

[request startSynchronous];
Jamie Pinkham
And that is the best idea :).
Jacek