文件下载的三种方式

文件下载的三种方式

标签: 断点续传AFN文件下载
  1420人阅读  评论(0)  收藏  举报
  分类:

目录(?)[+]

文件下载一(不支持断点续传)


这种下载方式用的场合比较少,逻辑比较复杂,代码量也比较大。

主要的处理在两个代理方法中

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{  
  2.     if (self.currentLengthreturn;  
  3.     //文件路径  
  4.     NSString * caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];  
  5.     NSString * filepath = [caches stringByAppendingPathComponent:@"file.zip"];  
  6.     NSLog(@"%@",filepath);  
  7.     _path = filepath;  
  8.     //创建一个空的文件到沙河中  
  9.     NSFileManager * mgr = [NSFileManager defaultManager];  
  10.     [mgr createFileAtPath:filepath contents:nil attributes:nil];  
  11.       
  12.     //创建一个用来写数据的文件句柄  
  13.     self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];  
  14.       
  15.     //获取文件的大小  
  16.     self.totalLength = response.expectedContentLength;  
  17.     NSLog(@"--%lld",self.totalLength);  
  18.     //    68186536  
  19. }  

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  *  2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次) 
  3.  * 
  4.  *  @param data       这次返回的数据 
  5.  */  
  6. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{  
  7.     //移动到文件的最后面  
  8.     [self.writeHandle seekToEndOfFile];  
  9.     //将数据写入到沙河  
  10.     [self.writeHandle writeData:data];  
  11.     //     NSLog(@"%@",data);  
  12.     //累计文件的长度  
  13.     self.currentLength += data.length;  
  14.     self.speed = [CountBytes CountBytesBy:data.length];  
  15.     self.CircleView.progress = (double)self.currentLengthself.totalLength;  
  16. }  

文件下载二(支持断点续传)


所谓断点续传就是在某个时刻暂停后,再次下载的时候从之前的进度开始,这就需要我们记录下暂停之前下载数据。

ok,我们只看暂停和再次开始的代码
暂停的代码

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (IBAction)pauseClicked:(id)sender {  
  2.       
  3.     [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {  
  4.         _resumeData = resumeData;  
  5.         _task = nil;  
  6.     }];  
  7.       
  8. }  

再次恢复下载的代码

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (IBAction)continueClicked:(id)sender{  
  2.     self.task = [self.session downloadTaskWithResumeData:self.resumeData];  
  3.     [self.task resume];  
  4.     self.resumeData = nil;  
  5. }  

文件下载三(支持断点续传)


这种下载方式是站在巨人的肩膀上,这个巨人就是伟大的AFN,在这里我将其封装成了下载工具类,只需要传下载路径就ok,然后根据block返回的数据进行刷新线程。

核心代码

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. + (NSURLSessionDownloadTask *)downloadFileWithUrl:(NSString *)url DownloadProgress:(DownloadProgress)progress DownloadCompletion:(CompletionState)completion{  
  2.     // 1、 设置请求  
  3.     NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];  
  4.     // 2、初始化  
  5.     NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];  
  6.     AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];  
  7.     // 3、开始下载  
  8.     NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {  
  9.         progress(1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount,1.0 * downloadProgress.totalUnitCount,1.0 * downloadProgress.completedUnitCount);  
  10.     } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {  
  11.         //这里要返回一个NSURL,其实就是文件的位置路径  
  12.         NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];  
  13.         //使用建议的路径  
  14.         path = [path stringByAppendingPathComponent:response.suggestedFilename];  
  15.         NSLog(@"%@",path);  
  16.         return [NSURL fileURLWithPath:path];//转化为文件路径  
  17.     } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {  
  18.         //如果下载的是压缩包的话,可以在这里进行解压  
  19.           NSLog(@"----%@---%d---%@",error.domain,error.code,error);  
  20.         //下载成功  
  21.         if (error == nil) {  
  22.             completion(YES,@"下载完成",[filePath path]);  
  23.         }else{//下载失败的时候,只列举判断了两种错误状态码  
  24.             NSString * message = nil;  
  25.             if (error.code == - 1005) {  
  26.                 message = @"网络异常";  
  27.             }else if (error.code == -1001){  
  28.                 message = @"请求超时";  
  29.             }else{  
  30.                 message = @"未知错误";  
  31.             }  
  32.             completion(NO,message,nil);  
  33.         }  
  34.     }];  
  35.     return task;  
  36. }  

代码传送门: https://github.com/fuzongjian/DownloadStudy.git
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值