且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AFNetworking +暂停/恢复下载大文件

更新时间:2023-01-05 13:24:01

您可以使用AFDownloadRequestOperation来执行此操作。

You can use AFDownloadRequestOperation to do this.

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"....zip"]];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"....zip"];
    AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:path shouldResume:YES];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", path);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
        NSLog(@"Operation%i: bytesRead: %d", 1, bytesRead);
        NSLog(@"Operation%i: totalBytesRead: %lld", 1, totalBytesRead);
        NSLog(@"Operation%i: totalBytesExpected: %lld", 1, totalBytesExpected);
        NSLog(@"Operation%i: totalBytesReadForFile: %lld", 1, totalBytesReadForFile);
        NSLog(@"Operation%i: totalBytesExpectedToReadForFile: %lld", 1, totalBytesExpectedToReadForFile);
    }];
    [operations addObject:operation];

重新启动应用程序后,生成具有相同网址的请求,它将恢复下载。
shouldResume:YES工作

After you restart your app, and generate the request having a same url, it will resume downloading. "shouldResume:YES" works