未调用NSURLSession委托

时间:2015-11-19 21:37:29

标签: ios objective-c nsurlsession

我想知道为什么我的委托方法-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location没有被调用。有我的代码:

- (void)viewDidLoad {
    [self createSessionWithDelegate];
    [super viewDidLoad];
}

- (void)createSessionWithDelegate {
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://example.com/my-expected-image.jpg"]];
    [task resume];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
    if (downloadedImage){
        NSLog(@"Got image!");
    }

    // Perform UI changes in main thread
    dispatch_async(dispatch_get_main_queue(), ^{
        self.myImageView.image = downloadedImage;
    });
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    NSLog(@"%f / %f", (double)totalBytesWritten, (double)totalBytesExpectedToWrite);    
}

另外我想补充说,我的方法:-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite正常工作(它显示输出我得到了多少字节)。

1 个答案:

答案 0 :(得分:2)

您是否尝试实施

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

查看是否返回了一些错误?