我有一个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];
}
}
NSURLConnection''sendAsynchronousRequest'在iOS 9中已弃用。(事实上,几乎每个部分的NSURLConnection都已弃用。)使用2个主要操作系统版本之前弃用的API进行新开发并不明智。我建议使用'NSURLSession'重写你的代码。 –
UpdateProgressBar中的代码看起来像是这个问题的适当部分。 – danh
我添加了UpdateProgressBar代码。 –