我正在尝试使用同一会话和不同的下载任务来下载多个图像,但是只能下载第一个图像。在didFinishDownloadingToURL中,我使用if条件来识别下载任务,并将其设置为特定的imageView。
以下是我的代码,请耐心等待:
以下是我的代码,请耐心等待:
@interface ViewController ()
{
NSURLSessionConfiguration *sessionConfiguration;
NSURLSessionDownloadTask *firstDownloadTask;
NSURLSessionDownloadTask *secondDownloadTask;
NSURLSession *session;
UIImageView *firstImageHolder;
UIImageView *secondImageHolder;
}
@end
- (void)viewDidLoad
{
NSString *firstDownloadLink = @"http://letiarts.com/letiarts2014/wp-content/uploads/2014/04/icon_game.png";
sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
firstImageHolder = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
[_viewImages addSubview: firstImageHolder];
firstDownloadTask = [session downloadTaskWithURL:[NSURL URLWithString:firstDownloadLink]];
[firstDownloadTask resume];
//2
NSString *secondDownloadLink = @"http://downloads.bbc.co.uk/skillswise/images/promo/prefab-maths-game-336x189.jpg";
secondImageHolder = [[UIImageView alloc] initWithFrame:CGRectMake(50, 0, 45, 45)];
[_viewImages addSubview: secondImageHolder];
secondDownloadTask = [session downloadTaskWithURL:[NSURL URLWithString:secondDownloadLink]];
[secondDownloadTask resume];
}
在didFinishDownloadingToURL方法中:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSData *data = [NSData dataWithContentsOfURL:location];
if (downloadTask == firstDownloadTask) {
UIImage *theImage1 = [UIImage imageWithData:data];
[firstImageHolder setImage:theImage1];
NSLog(@"DOWNLOAD FIRST IMAGE FINISHED");
}
//download finished
if (downloadTask == secondDownloadTask) {
UIImage *theImage2 = [UIImage imageWithData:data];
[secondImageHolder setImage:theImage2];
NSLog(@"DOWNLOAD SECOND IMAGE FINISHED");
}
}
非常感谢您提前阅读!