Делегаты NSURLSessionDownloadTask не запускаются

Я играю с учебником для NSURLSession. Я могу успешно загрузить изображение, однако делегаты процесса загрузки и завершения загрузки не запускаются. Вот код:

- (void)viewDidLoad
{
    [super viewDidLoad];


    NSString * imageUrl = @"http://ichef.bbci.co.uk/naturelibrary/images/ic/credit/640x395/r/ro/rock_pigeon/rock_pigeon_1.jpg";

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession * session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

    //Download image.
    NSURLSessionDownloadTask * getImageTask = [session downloadTaskWithURL:[NSURL URLWithString:imageUrl]

                                               completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

                                                   if (error) {
                                                       NSLog(@"Error sadly for you is %@", [error localizedDescription]);
                                                   }

                                                   UIImage * downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];



                                                   dispatch_async(dispatch_get_main_queue(), ^ {
                                                       self.imageView.image = downloadedImage;
                                                   });

                                               }];

    [getImageTask resume];

    // Do any additional setup after loading the view, typically from a nib.
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"Temporary File :%@\n", location);
    NSError *err = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSURL *docsDirURL = [NSURL fileURLWithPath:[docsDir stringByAppendingPathComponent:@"out1.zip"]];
    if ([fileManager moveItemAtURL:location
                             toURL:docsDirURL
                             error: &err])
    {
        NSLog(@"File is saved to =%@",docsDir);
    }
    else
    {
        NSLog(@"failed to move: %@",[err userInfo]);
    }

}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //You can get progress here
    NSLog(@"Received: %lld bytes (Downloaded: %lld bytes)  Expected: %lld bytes.\n",
          bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}

И в файле .h:

#import <UIKit/UIKit.h>

@interface SGGViewController : UIViewController <NSURLSessionDelegate> {
    IBOutlet UIImageView * imageView;
}

@property (nonatomic, strong) IBOutlet UIImageView * imageView;

@end

Может кто подскажет как исправить?


person GuybrushThreepwood    schedule 12.02.2014    source источник


Ответы (2)


У вас уже есть делегат, поэтому вы можете пропустить completionHandler/блочную форму создания задачи и полностью использовать делегата.

Беглый взгляд на святой сценарий не сообщил мне ничего авторитетного о том, предотвратит ли указание обработчика завершения запуск методов делегата, но в этих отношениях многое кажется взаимоисключающим.

Если вы еще этого не сделали, я бы посоветовал вам добавить –URLSession:task:didCompleteWithError: к вашему делегату. Он может зафиксировать проблемы, которые могут пропустить методы делегирования загрузки.

person Clay Bridges    schedule 12.02.2014
comment
Это исправило? Если да, то какая часть? - person Clay Bridges; 12.02.2014
comment
Это была моя проблема. Наличие блока завершения, кажется, отменяет вызов всех методов делегата, а не только метода didFinishDownloadingToURL. - person Scooter; 06.06.2014

Используйте NSUrlRequest Теперь делегаты будут вызывать . Надеюсь, это сработает

 - (void)viewDidLoad
{
    [super viewDidLoad];

    NSURLSessionDownloadTask *downloadTask =nil;
    NSString * imageUrl = @"http://fc05.deviantart.net/fs71/i/2012/180/8/f/ios_6_logo_psd___png_by_theintenseplayer-d55eje9.png";
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession * session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]] ;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];

    downloadTask = [session downloadTaskWithRequest:request];
    [downloadTask resume ];

    /*
    NSURLSessionDownloadTask * getImageTask = [session downloadTaskWithURL:[NSURL URLWithString:imageUrl]

                                                         completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

                                                             if (error) {
                                                                 NSLog(@"Error sadly for you is %@", [error localizedDescription]);
                                                             }

                                                             UIImage * downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];



                                                             dispatch_async(dispatch_get_main_queue(), ^ {
                                                                 //self.imageView.image = downloadedImage;
                                                             });

                                                         }];

    [getImageTask resume];
     */

    // Do any additional setup after loading the view, typically from a nib.
}
person ManiaChamp    schedule 12.02.2014