在特定的viewController
中有几个文件要下载。当用户点击特定文件的下载时,会出现一个progressView
,显示下载的数据量。此外,在特定时间可以下载多个文件。由于文件相当大,完成下载需要几分钟时间。问题是,当我转到另一个ViewController
时,所有下载都会停止,我必须留在下载的ViewController
上,等待下载完成。我正在使用NSURLSession
下载数据。即使下载ViewController
被取消,有没有办法让下载继续进行?
一种选择是我将代码传输到appDelegate
。有其他方便的方法做这项任务吗。
尝试查看AFNetworkinghttps://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);
}];