- (void)downloadUrls:(NSArray *)urls completionBlock:(void(^)(NSArray *results))completionBlock {
NSMutableArray *results = [NSMutableArray array];
BOOL finishAll = NO;
for(NSString *url in urls) {
[Downloader startFetch:url completion:^(id response){
[results addObject:response];
}];
}
if(finishAll){
completionBlock(results);
}
}
我需要使用此方法下载许多网址,如果所有网址都已下载,请调用completionBlock,startFetch:
是异步方法,那么有没有办法确定所有任务已按顺序完成调用completionBlock?
答案 0 :(得分:2)
不在downloadURLs:completionBlock:
内,不,但您可以检查您是否在startFetch:completion:
完成区内的最后一项。
[Downloader startFetch:url completion:^(id response){
[results addObject:response];
if( [results count] == [urls count] ){
completionBlock(results);
}
}];
或
NSMutableArray *results = [NSMutableArray array];
id lastURL = [results lastObject];
for(NSString *url in urls) {
[Downloader startFetch:url completion:^(id response){
[results addObject:response];
if( url == lastURL ){
completionBlock(results);
}
}];
}