使用AFNetworking在iOS中下载文件

编程入门 行业动态 更新时间:2024-10-28 14:36:15
本文介绍了使用AFNetworking在iOS中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想能够使用AFNetworking下载文件,该文件支持:ProgressBar,暂停和恢复下载。

I want to be able to download a file using AFNetworking that supports: ProgressBar, Pausing, and Resuming download.

我自己接近这个除了它不支持暂停或恢复:

Approaching this on my own I was able to come up with this code, except that it doesn't support pausing or resuming:

-(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]; }

事实上,我不知道如何管理暂停和简历。

Thing is, I don't know how to manage pause & resume.

查看他们的文档:( https:// github/AFNetworking/AFNetworking ),他们提供了一种不同的下载方式:

Looking at their documentation: ( github/AFNetworking/AFNetworking ) they offer a different approach to download the file:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"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];

我希望在我的iOS文档文件夹中正确命名fw4.pdf。但是,这是记录的结果:

I would expect the "fw4.pdf" to be named properly in my iOS' documents folder. However, this is the logged result:

文件下载到:file:///Users/myName/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/ F4C3BC41-70B4-473A-B1F6-D4BC2A6D0A4F / Documents / CFNetworkDownload_ZkSW5n.tmp

File downloaded to: file:///Users/myName/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/F4C3BC41-70B4-473A-B1F6-D4BC2A6D0A4F/Documents/CFNetworkDownload_ZkSW5n.tmp

上述文件下载但带有奇怪的临时名称。

The above file IS downloaded but with the weird temp name.

我在自己的代码中意识到我使用了一个AFHTTPRequestOperation对象,而他们使用的是AFURLSessionManager。

I realize in my own code I'm using a "AFHTTPRequestOperation" object whereas they're using a "AFURLSessionManager".

任何想法?

推荐答案

- (void)downloadFile{ NSURL *url = [NSURL URLWithString:@"198.61.234.81/expris/uploads/attachments/file_1.pdf"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFHTTPSessionManager *session = [AFHTTPSessionManager manager]; NSProgress *progress; NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]]; //Here is change return [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]]; }completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { [progress removeObserver:self forKeyPath:@"fractionCompleted" context:NULL]; dispatch_async(dispatch_get_main_queue(), ^(void){ NSLog(@"File downloaded to: %@", filePath); }); }]; [downloadTask resume]; [progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ NSProgress *progress = (NSProgress *)object; NSLog(@"Progress… %f", progress.fractionCompleted); }

更多推荐

使用AFNetworking在iOS中下载文件

本文发布于:2023-06-04 22:09:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/506066.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   AFNetworking   iOS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!