NSURLSessionDownloadTask代理未触发

3

我正在尝试一个关于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

有人能建议如何修复吗?
2个回答

7

现在使用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.
}

5
您已经有了代理,因此您可以跳过任务创建的completionHandler/block形式,并全面使用代理。
快速浏览官方文档并没有告诉我关于指定完成处理程序是否会阻止代理方法被触发的权威信息,但是这种关系似乎存在很多相互排斥的情况。
如果您还没有添加–URLSession:task:didCompleteWithError:到您的代理中,我建议您这样做。它可能会捕获纯下载代理方法可能会错过的问题。

修好了吗?如果修好了,是哪一部分修好了? - Clay Bridges
这是我的问题。在那里放置完成块似乎会压制所有委托方法的调用,而不仅仅是didFinishDownloadingToURL方法。 - Scooter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接