objective-c - NSURLSessionDownloadTask 委托(delegate)未触发

标签 objective-c cocoa-touch ios7 nsurlconnection nsurlsession

我正在研究 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

有人可以建议如何修复吗?

最佳答案

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

关于objective-c - NSURLSessionDownloadTask 委托(delegate)未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21726270/

相关文章:

ios - 检测应用程序是否从推送通知启动/打开,然后将其重定向到特定的 View Controller

objective-c - 使用ExtAudioFile read读取音频文件时,是否可以不连续读取音频 float ?

iphone - 如何获取 MKMapView map 的中心?

iphone - ASIhttprequest 将响应转换为 NSString

ios - 在不离开应用程序的情况下打开 App Store 链接,可能吗?

ios - 使用重叠按钮对 UIImageView 进行动画处理

iphone - iPhone 地址簿显示空白字段,如何调试?

ios - 为什么 UIPopoverController 不是 UIViewController 的子类?

ios - 如何在 iOS 8 上强制启动图像而不是启动屏幕?

uitableview - 如果未声明 heightForRowAtIndexPath,iOS 7.1 会崩溃