我有一个iPad应用程序,我可以下载图像列表,并在下载图像时更新进度条。我似乎无法获得进度条和图像下载以匹配。进度条始终在图像下载完成之前完成。我有一个方法UpdateProgressBar,每次下载图像时都应该增加进度条。
-(void)DownloadPhoto{
NSMutableArray *failedDownloads = [[NSMutableArray alloc]init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
listPhoto = [CoreDataRead GetPhotoList:[self selectedAccountGuid]];
dispatch_group_t downloadGroup = dispatch_group_create();
for (Photo *item in listPhoto) {
NSString *imageName = item.photoName;
NSString *myURL = [NSString stringWithFormat:@"%@%@", @"http://acimagedownload.com/photos/", imageName];
NSURL *url = [NSURL URLWithString:myURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
dispatch_group_enter(downloadGroup);
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil && data != nil)
{
if (data != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"%@%@",item.guid, @".png"]];
[data writeToFile:path atomically:YES];
NSLog(@"Photo Downloaded %@!", @"");
}
else
{
NSLog(@"image is not downloaded");
}
}
else if (connectionError != nil)
{
[failedDownloads addObject:myURL];
NSLog(@"Error %@",[connectionError description]);
}
else
{
[failedDownloads addObject:myURL];
NSLog(@"Image Download Failed %@!", @"");
}
dispatch_group_leave(downloadGroup);
dispatch_async(dispatch_get_main_queue(), ^{
[self UpdateProgressBar];
});
}];
dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self DownloadVideo];
});
});
}
-(void)UpdateProgressBar{
currentTask = currentTask + 1;
NSLog(@"Current Task %@!", [@(currentTask) stringValue]);
float progressPercentage = (float)currentTask/(float)taskCount;
[self.progressBar setProgress:progressPercentage animated:YES];
if(currentTask == taskCount){
[self ShowDoneAlert];
}
}
答案 0 :(得分:0)
如果没有看到updateProgressBar
方法,为什么你会得到这种行为很难说,但我注意到的一件事是你的dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER);
在你的循环中。
所以会发生什么,你进入循环的第一次迭代,在它结束时,线程执行停止并等待第一个dispatch_group_leave
。之后继续下一次迭代,依此类推。
如果这是期望的行为(但我怀疑它,我认为您实际上希望您的下载并行运行),您应该使用dispatch_semaphore_t
甚至是串行队列。