0
votes

I am using ASIHTTPRequest to download some data.

I have the following in a method:

// Request 1
request1.tag = 1;
[request1 setDelegate:self];
[request startAsynchronous];

// Request 2
request2.tag = 2;
[request2 setDelegate:self];
[request2 startAsynchronous];

// Call third request method
[self callThirdRequest];

Now from within callThirdRequest, I am grabbing some data that has been downloaded from request2 and in there, I am calling startAsynchronous. The reason I have the calling of the third request in a separate method is because it will get invoked more than once. After putting some console outputs, it seems that callThirdRequest is being invoked before request2 starts its download. Therefore, when callThirdRequest tries to grab some data which should have been downloaded by request2, it does not work as there is no data.

Why is that? How can I make sure callThirdRequest is only called when request2 is done downloading?

Thanks,

3

3 Answers

2
votes

When a request is run asynchronously, the rest of your code will continue to run at the same time. Your first two requests are doing exactly that. You have two options.

You can run the second request synchronously. (Not a good idea, since your app will appear "frozen" until the second request completes. Also, using this method won't help you if the second request, in your list of three, fails.)

A much better idea would be to use delegate callback methods. This is the better way of dealing with this, for two reasons. First of all, you can handle failed requests properly, and also, you can handle successful requests properly. Yu want something like this:

// Request 2
request2.tag = 2;
[request2 setDelegate:self];
[request2 startAsynchronous];



- (void)requestFinished:(ASIHTTPRequest *)request{
   if(request.tag == 2){
     [self callThirdRequest];
   }
}

Make sure to check the request in the delegate callback, to ensure that it's the "second" one, so that you don't end up firing the wrong action at the wrong time. In this case, I used the "tag" property of the request. If you would have retained the request as a property of your class, you can just check for that as well.

1
votes

That is because request2 is running asynchronous. You should start the 3rd request in the request-did-finish-delegate-method of request2!

1
votes

The reason is startAsynchronous. An asynchronous call will operate on another thread. You need to set the delegate on request2 and then call the third request when request2 is finished.

    // Request 2
    request2.tag = 2;
    [request2 setDelegate:self];
    [request2 startAsynchronous];

...

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [self callThirdRequest];
}