我一直在使用NSURLConnection's
sendAsynchronousRequest:queue:completionHandler:
方法,这很棒。但是,我现在需要连续发出多个请求。
我如何在使用这个伟大的异步方法的同时做到这一点呢?
发布于 2012-02-23 16:53:20
根据你想要的行为,有很多方法可以做到这一点。
您可以一次发送一组异步请求,跟踪已完成的请求的数量,并在它们全部完成后执行某些操作:
NSInteger outstandingRequests = [requestsArray count];
for (NSURLRequest *request in requestsArray) {
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
[self doSomethingWithData:data];
outstandingRequests--;
if (outstandingRequests == 0) {
[self doSomethingElse];
}
}];
}
您可以将这些块链接在一起:
NSMutableArray *dataArray = [NSMutableArray array];
__block (^handler)(NSURLResponse *response, NSData *data, NSError *error);
NSInteger currentRequestIndex = 0;
handler = ^{
[dataArray addObject:data];
currentRequestIndex++;
if (currentRequestIndex < [requestsArray count]) {
[NSURLConnection sendAsynchronousRequest:[requestsArray objectAtIndex:currentRequestIndex]
queue:[NSOperationQueue mainQueue]
completionHandler:handler];
} else {
[self doSomethingElse];
}
};
[NSURLConnection sendAsynchronousRequest:[requestsArray objectAtIndex:0]
queue:[NSOperationQueue mainQueue]
completionHandler:handler];
或者,您可以在一个异步块中同步完成所有请求:
dispatch_queue_t callerQueue = dispatch_get_current_queue();
dispatch_queue_t downloadQueue = dispatch_queue_create("Lots of requests", NULL);
dispatch_async(downloadQueue, ^{
for (NSRURLRequest *request in requestsArray) {
[dataArray addObject:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]];
}
dispatch_async(callerQueue, ^{
[self doSomethingWithDataArray:dataArray];
});
});
});
附注:如果你使用其中的任何一个,你应该添加一些错误检查。
https://stackoverflow.com/questions/9409211
复制相似问题