在我的 iOS 应用程序中,我使用AFNetworking
库来管理所需的 HTTP 操作。
我创建了一种下载文件的方法:
+ (void)downloadFile:(File *)file progress:(void (^)(NSUInteger receivedBytes, long long totalReceivedBytes, long long totalExpectedBytes))progress success:(void (^)())success failure:(void (^)(NSError *error))failure
{
NSURLRequest *request = [NSURLRequest requestWithURL:file.url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:[FCFileManager pathForTemporaryDirectoryWithPath:file.key.lastPathComponent] append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
progress(bytesRead, totalBytesExpectedToRead, totalBytesExpectedToRead);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
success();
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
failure(error);
}];
[operation start];
}
虽然,这种方法存在问题。如果正在取消下载(强制退出),该文件仍然可以在应用程序目录中找到。如何创建文件下载,仅在下载成功完成后将文件保存到文档目录?