Ios 如何在重启应用程序后恢复下载任务(NSURLSessionDownloadTask)

Ios 如何在重启应用程序后恢复下载任务(NSURLSessionDownloadTask),ios,afnetworking,afnetworking-2,nsurlsession,Ios,Afnetworking,Afnetworking 2,Nsurlsession,我添加“下载任务”并终止应用程序进程 运行应用程序后,获取[manager downloadTasks];并恢复所有。 但文件未加载到Documets目录 我使用AF2.0() 完整代码- 我注意到,下载完成后,在finder中查找文档目录时,文件不存在。但是,当从应用程序访问该文件时,它会找到它。一段时间后(一分钟内),文件最终出现在documents目录中。这可能是一个仅与模拟器相关的问题 // // DownloadsViewController.m // #import "Downl

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

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

我使用AF2.0()

完整代码-


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

//
//  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