【问题标题】:How to Continue data download in other ViewControllers如何在其他 ViewController 中继续下载数据
【发布时间】:2015-11-14 08:13:48
【问题描述】:

在特定的viewController 中有几个文件可供下载。当用户点击下载特定文件时,会出现progressView 以显示下载的数据量。同样在特定时间可以下载多个文件。由于文件很大,所以需要几分钟才能完成下载。问题是当我转到另一个ViewController 时,所有下载都停止了,我必须继续下载ViewController 并等待下载完成。我正在使用NSURLSession 下载数据。有没有办法在下载ViewController 被取消的情况下继续下载?

一个选项是我将代码转移到appDelegate。有没有其他方便的方法来完成这项任务。

【问题讨论】:

  • 如果您需要一些我在这里忘记提及的额外信息,请提及
  • 问题是,你可能正在使用主线程执行下载任务,为什么不使用异步线程在后台下载文件,仍然在主线程将进度更新发送到 UI?
  • 但问题在于每个下载任务,我已经制作了一个具有多个标志和属性的对象,如下载数据、progressView 等.....如何实现

标签: ios objective-c uiviewcontroller nsurlsession nsurlsessiondownloadtask


【解决方案1】:

尝试查看 AFNetworking https://github.com/AFNetworking/AFNetworking

您可以在 Appdelegate 中定义这部分,但一定要让它们可见(属性)

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

然后在任何视图中获取它们并开始下载任务

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];

NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2015-12-03
    • 2019-01-23
    • 1970-01-01
    • 2012-06-21
    相关资源
    最近更新 更多