ios - 重启应用后如何恢复下载任务(NSURLSessionDownloadTask)

标签 ios afnetworking afnetworking-2 nsurlsession

我添加“下载任务”并终止应用进程。

运行app后,获取[manager downloadTasks];并恢复所有。 但文件未加载到 Documets 目录中。

我使用 AFNetworking 2.0 ( https://github.com/AFNetworking/AFNetworking )

完整代码 - https://github.com/nullproduction/FileDownloader

//
//  DownloadsViewController.m
//

#import "DownloadsViewController.h"

@implementation DownloadsViewController

- (id)init
{
    [self printDocumentsPath];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"downloads"];

    manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSArray *downloadTasks = [manager downloadTasks];

    if (downloadTasks.count)
    {
        NSLog(@"downloadTasks: %@", downloadTasks);
        // resume all
        for (NSURLSessionDownloadTask *downloadTask in downloadTasks)
        {
            [downloadTask resume];
        }
    }

    return [super init];
}

- (void)addDownloadTask:(id)sender
{
    NSURL *URL = [NSURL URLWithString:@"http://www.rarlab.com/rar/wrar500.exe"];

    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request
    progress:nil
    destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
       NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
        return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
         NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];

    NSLog(@"%d", downloadTask.taskIdentifier);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"addDownloadTask" style:UIBarButtonItemStyleBordered target:self action:@selector(addDownloadTask:)];
}

- (void)printDocumentsPath
{
    NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"%@", documentsDirectoryPath);
}



@end

最佳答案

我注意到,下载完成后在 finder 中查看文档目录时,文件不存在。但是,当从应用程序访问文件时,它会找到它。一段时间后(一分钟内),该文件最终出现在 documents-dir 中。这可能是仅与模拟器相关的问题。

关于ios - 重启应用后如何恢复下载任务(NSURLSessionDownloadTask),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19790414/

相关文章:

ios - 你如何将 int 转换为 int64_t

ios - 如何在 ios 9 的 swift 3 中使用 Alamofire?

ios - TableViewController 中的表在接收到数据之前被填充

ios - 在 AFNetworking 2.x 中替换 AFJSONRequestOperation

ios - "NSURLErrorDomain"- 代码 : 18446744073709550594 Ajax call on Xcode 7

iphone - UIWebView 调整大小慢

ios - 从框架呈现 UIViewController

ios - NSoperationQueue阻塞主线程

ios - 使用 AFNetworking 缓存较大的图像

uiwebview - AFNetworking 证书固定 UIWebView