依靠NSOutputStream,NSURLSession,NSURLSessionDataTask创建一个支持断点下载的任务
来源:互联网 发布:painter mac 2017 破解 编辑:程序博客网 时间:2024/06/02 00:16
//// ViewController.m// BreakPointDownload//// Created by hq on 16/4/18.// Copyright © 2016年 hanqing. All rights reserved.//#import "ViewController.h"#import "NSString+Hash.h"//定义文件等下载路径cache路径#define HQFilePath NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject#define HQFileURLString @"http://xxx/resources/videos/minion_01.mp4"//定义我们的文件名,直接只用url因为每个url对应一个文件是唯一的#define HQFileName HQFileURLString.md5String@interface ViewController () <NSURLSessionDataDelegate>@property (weak, nonatomic) IBOutlet UILabel *downloadStatus;@property (weak, nonatomic) IBOutlet UIProgressView *pro;@property (weak, nonatomic) IBOutlet UILabel *downSize;@property (weak, nonatomic) IBOutlet UIButton *loadBut;//文件等总大小@property(nonatomic,assign) NSInteger fileTotalSize;//当前文件下载了多少@property(nonatomic,assign) NSInteger fileCurrentSize;@property(nonatomic,strong) NSOutputStream *outputStream;@property(nonatomic,strong) NSURLSessionDataTask *task;- (IBAction)butClicked:(UIButton *)sender;@property(nonatomic,strong) NSOperationQueue *queue;@end@implementation ViewController-(NSURLSessionDataTask *)task{ if (!_task) { NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:HQFileURLString]]; //指定从哪个位置继续下载 [request setValue:[NSString stringWithFormat:@"bytes=%ld-",[self getCurrentDownloadSize]] forHTTPHeaderField:@"Range"]; _task=[session dataTaskWithRequest:request]; } return _task;}-(NSOutputStream *)outputStream{ if (!_outputStream) { _outputStream=[[NSOutputStream alloc]initToFileAtPath:[HQFilePath stringByAppendingPathComponent:HQFileName] append:YES]; } return _outputStream;}- (void)viewDidLoad { [super viewDidLoad]; NSString *plistPath=[HQFilePath stringByAppendingPathComponent:@"fileSize.plist"]; //获取文件的总大小 NSInteger totalSize=[[NSDictionary dictionaryWithContentsOfFile:plistPath][HQFileName] integerValue]; if (totalSize==0) { self.downSize.hidden=YES; self.pro.progress=0; } else{ self.downSize.hidden=NO; self.downSize.text=[NSString stringWithFormat:@"%.0f%",1.0*[self getCurrentDownloadSize]/totalSize*100]; self.pro.progress=1.0*[self getCurrentDownloadSize]/totalSize; } if (totalSize==[self getCurrentDownloadSize]&&totalSize!=0) { self.downloadStatus.hidden=NO; self.loadBut.enabled=NO; [self.loadBut setTitle:@"开始下载" forState:UIControlStateNormal]; } NSLog(@"%@",[HQFilePath stringByAppendingPathComponent:HQFileName]); }- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; }- (IBAction)butClicked:(UIButton *)sender { if ([self.loadBut.titleLabel.text isEqualToString:@"开始下载"]) { [self.task resume]; [self.loadBut setTitle:@"暂停" forState:UIControlStateNormal]; } else if([self.loadBut.titleLabel.text isEqualToString:@"暂停"]){ [self.task suspend]; [self.loadBut setTitle:@"继续下载" forState:UIControlStateNormal]; } else{ [self.task resume]; [self.loadBut setTitle:@"暂停" forState:UIControlStateNormal]; } }-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{ [self.outputStream open]; //必须开启才能接收服务端的请求 completionHandler(NSURLSessionResponseAllow); //表示服务器当前能返回给我们的文件等大小 self.fileTotalSize=[response.allHeaderFields[@"Content-Length"] integerValue]+[self getCurrentDownloadSize]; //把文件的总大小写入我们的plist文件,key就用我们的文件名 NSString *plistPath=[HQFilePath stringByAppendingPathComponent:@"fileSize.plist"]; NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; if (dict==nil) { dict=[NSMutableDictionary dictionary]; } //用我们的md5的url当作key dict[HQFileName]=@(self.fileTotalSize); [dict writeToFile:plistPath atomically:YES]; }-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{ [self.outputStream write:[data bytes] maxLength:data.length]; self.fileCurrentSize=[self getCurrentDownloadSize]; [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.downSize.hidden=NO; self.pro.progress=(1.0*self.fileCurrentSize/self.fileTotalSize); self.downSize.text=[NSString stringWithFormat:@"%.0f%%",(1.0*self.fileCurrentSize/self.fileTotalSize)*100]; }]; NSLog(@"%ld",self.fileCurrentSize); }-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ if (error) { return; } [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.downloadStatus.hidden=NO; self.loadBut.enabled=NO; [self.loadBut setTitle:@"开始下载" forState:UIControlStateNormal]; }]; [self.outputStream close]; self.outputStream=nil; self.task=nil; }//判断文件现在已经下载了多少-(NSInteger) getCurrentDownloadSize{ NSDictionary *dict=[[NSFileManager defaultManager] attributesOfItemAtPath:[HQFilePath stringByAppendingPathComponent:HQFileName] error:nil]; return [dict[@"NSFileSize"] integerValue]; }@end
1 0
- 依靠NSOutputStream,NSURLSession,NSURLSessionDataTask创建一个支持断点下载的任务
- 文件断点下载(NSURLSessionDataTask)的使用
- iOS之网络—— NSURLSessionDataTask文件离线断点下载、NSURLSession文件上传、AFN基本使用、Cocoapods安装
- ios:NSURLSessionDataTask做文件断点下载
- NSURLSession实现断点下载
- 【iOS】NSURLSession断点下载
- NSURLSession实现断点下载
- NSURLSession 断点下载
- iOS NSURLSession后台下载多个任务,支持断点续传
- NSURLSession post -- NSURLSessionDataTask
- 网上只写了一个文件断点下载的例子! 我仿照别人得例子 自己增加了自己代码,异步下载文件 支持断点下载 多任务下载! 如有问题 请联系我
- android实现多任务多线程支持断点下载的下载软件
- android 下载文件(支持多任务,支持断点.....)
- 使用 NSURLSession 开发一个支持后台下载和断点续传的下载工具
- NSURLSession NSURLConnection下载大文件 断点下载
- 准备写一个http下载,支持断点下载,多线程下载
- NSURL 、NSURLRequest、NSURLConnection、NSURLSession、NSURLSessionDataTask
- NSURLSession前台下载/后台下载/断点下载的代理执行路径(一)
- C Primer Plus(第五版) 第十四章 第八题
- unity 编辑器扩展控件属性变化监听 BeginChangeCheck
- poj 3692 最大团(二分图匹配,最大独立集)
- C++_运算符重载
- 【转】ssh scp 免密码方法
- 依靠NSOutputStream,NSURLSession,NSURLSessionDataTask创建一个支持断点下载的任务
- Http和Https的区别
- 解决android:layout_marginBottom在RelativeLayout中无效的bug
- HTML第一课:B/S结构&C/S结构、HTML、六种常用标签
- 【CodeVS 1477】 永无乡 |Splay
- android Fragment中遇到的问题
- Struts的基本概念
- 高分辨率屏幕下有哪些windows系统界面是模糊的
- 1808: [Ioi2007]training 训练路径|树形DP