我希望能够使用支持以下功能的 AFNetworking 下载文件:ProgressBar、Pausing 和 Resuming download。
我自己接近这个我能够想出这段代码,除了它不支持暂停或恢复:
-(void)downloadFile:(NSString *)UrlAddress indexPathofTable:(NSIndexPath *)indexPath
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:UrlAddress]];
NSString *pdfName = [self pdfNameFromURL:UrlAddress];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:pdfName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"Successfully downloaded file to %@", path);
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error: %@", error);
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
//do something in this line with the calculation to cell
float progress = (float)totalBytesRead / totalBytesExpectedToRead;
[[NSNotificationCenter defaultCenter] postNotificationName:[NSString stringWithFormat:@"progress-%ld-%ld", (long)indexPath.section, (long)indexPath.row] object:@(progress)]; //Working reporting progress in cellForRowAtIndexPath.
//NSLog(@"Download = %f", progress);
}];
[operation start];
}
问题是,我不知道如何管理暂停和恢复。
查看他们的文档:(https://github.com/AFNetworking/AFNetworking)他们提供了一种不同的方法来下载文件:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://www.irs.gov/pub/irs-pdf/fw4.pdf"];
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];
我希望“fw4.pdf”在我的 iOS 文档文件夹中正确命名。但是,这是记录的结果:
文件下载到:file:///Users/myName/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/F4C3BC41-70B4-473A-B1F6-D4BC2A6D0A4F/Documents/CFNetworkDownload_ZkSW5n.tmp
上面的文件已下载,但临时名称很奇怪。
我意识到在我自己的代码中我使用的是“AFHTTPRequestOperation”对象,而他们使用的是“AFURLSessionManager”。
有任何想法吗?