ios - 如何在其他 ViewController 中继续下载数据

标签 ios objective-c uiviewcontroller nsurlsession nsurlsessiondownloadtask

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

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

最佳答案

尝试在 AFNetworking 上看看 https://github.com/AFNetworking/AFNetworking

您可以在 Appdelegate 中定义这部分,但请确保使它们可见(属性)

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

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

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);
    }];

关于ios - 如何在其他 ViewController 中继续下载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33706446/

相关文章:

ios - 在 View Controller 之间传递数据

iphone - 为什么我的 iPhone 应用程序崩溃并出现异常 "Could not load NIB in bundle"?

ios - 将数百个 PFObject 保存到 Parse 云

ios - 导航 Controller 的问题

objective-c - 滚动在 Google+ iPhone 应用程序中如何工作?

iphone 应用程序崩溃,没有任何控制台错误或崩溃日志 :

ios - 使用 UIViewController 类别发送电子邮件

objective-c - iOS – 回调的设计决策(使用 NSNotifications 或 AppDelegate)

iOS 7 UITableView 默认分隔符在重新排序后变得奇怪

ios - 收到推送通知时捕获