1

我开始使用 NSURLSession 实现下载方法,并成功地从多个请求中下载了不同的文件。但是现在我想添加一个进度轨道,但是没有触发下载进度的代表。

这是我的代码:

NSURLSessionConfiguration *defaultConfigObject = NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue:nil];

NSURLSessionDownloadTask * downloadTask = [defaultSession downloadTaskWithRequest:request completionHandler:^(NSURL * __nullable location,
                                                                 NSURLResponse * __nullable response, NSError * __nullable error) {

NSData *data = [NSData dataWithContentsOfURL:location];

[[NSFileManager defaultManager] createFileAtPath:docPath contents:data attributes:nil];

if ([[NSFileManager defaultManager] fileExistsAtPath:docPath]) {

NSDictionary *notificationDic = [[NSDictionary alloc] initWithObjectsAndKeys:docPath,@"docPath", item, @"item", nil];

[[NSNotificationCenter defaultCenter] postNotificationName: @"openFile" object:nil userInfo:notificationDic];

}

}];
[downloadTask resume];

我的头文件上有 NSURLSessionDownloadDelegate 。

我需要使用完成处理程序才能对文件执行不同的任务。

有什么办法可以做到吗?

4

3 回答 3

3

如果您使用downloadTaskWithRequest不带completionHandler参数的渲染,则将调用进度委托方法。显然,您必须将completionHandler块中当前的代码移动到didFinishDownloadingToURL方法中。但是如果你这样做,你会看到didWriteData被调用。

于 2015-07-03T03:22:45.223 回答
1

您必须通过以下方式开始下载:

- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;

并为您的进度实现委托方法:

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
                                       didWriteData:(int64_t)bytesWritten
                                  totalBytesWritten:(int64_t)totalBytesWritten
                          totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;

而且由于您需要在完成后执行各种任务,因此您还应该实现这个委托方法:

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
                          didFinishDownloadingToURL:(NSURL *)location;

本质上,完成处理程序例程是快速执行任务然后在完成后执行完成处理程序的“便利”例程。但他们不调用其他委托例程。

于 2015-07-03T03:32:48.283 回答
0

就我而言,问题是我让我的班级使用URLSessionDelegate而不是URLSessionDownloadDelegate. 即使我正在实施这些URLSessionDownloadDelegate方法。

于 2019-01-30T09:51:54.270 回答