series of http asynchronous request calls
I need to make a series of 开发者_JAVA百科http asynchronous request calls within a for loop . But then i would need to wait for the download to complete for a response before making the next request without crashing. So using NSNotification (or anything else) how can i handle this.
When you do a async request you wont be required to wait. However you need to handle the responses correctly. You can check the ASIHttpRequest library which currently seems to be the favorite of developers on SO. If you have to wait for the response then you are not doing it asynchronously.
Coming to using NSNotification, a better cleaner and simpler approach would be to use protocols. This way you implement the delegate and send you next request everytime the delegate method is called.
You want to run a number of serial requests in the background and wait for each request to finish before the next gets started. This is no different than running anything else in the background. Here is something I whipped up:
[self performSelectorInBackground:@selector(runRequests) ...];
- (void)runRequests
{
for (int i = 0; i < self.urls.count; i++) {
NSURL *url = [self.urls objectAtIndex:i];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous]; // Note: not asynchronous
// Handle response ...
ALog(@"%@ completed", url);
}
[[NSNotificationCenter defaultCenter]
postNotificationName:@"all requests completed!" object:nil];
}
I'm using ASIHTTRequest here, but using NSURLRequest works just as well in this case. The important thing is that the request is run to completion.
You can do it by using threads as follows
[NSThread detachNewThreadSelector:@selector(myMethod1) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(myMethod2) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(myMethod3) toTarget:self withObject:nil];
and so on........... You can pass your requests in these methods asynchronously.
精彩评论