开发者

Order of Requests in ASIHTTPRequest

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,


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.


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


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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜