如何使用相同的会话和不同的下载任务下载多个图像

Lau*_*fan 6 xcode ios nsurlsession

我试图使用相同的会话和不同的下载任务下载多个图像,如问题所示.我可以下载第一张图片而不是第二张图片.在didFinishDownloadingToURL中,我使用if条件来识别downloadTask并且对于某个downloadTask将其设置为某个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];
}
Run Code Online (Sandbox Code Playgroud)

在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");

    }
}
Run Code Online (Sandbox Code Playgroud)

先感谢您!

Lau*_*fan 1

代码很好,因为问题是在我的实际代码中我犯了一个错误,在第二份简历中我调用了第一个任务。