利用NSURLSession下载视频,图片,能实现断点续传
首先分析下载资源到本地,就得有URL ,点击btn ,就会解析网络地址,获取数据,就得有进度条控件
NSURLSession类的实现,通过委托代理模式去实现一些方法,需遵守<NSURLSessionDownloadDelegate>,委托代理设计模式在iOS开发中得到大量使用
利用NSURLConnection实现断点续传
1.NSURLSession,iOS7中推出的一个类,有取代NSURLConnection
2.实现文件的下载与上传,而NSURLSessionData有两个子类:NSURLSessionDownloadTask实现文件的下载和NSURLSessionUploadTask实现文件上传
3.NSURLSession的获取
NSURLSession 的获取通过NSURLSessionDownloadTaskDelegate的方法获取,但是必须遵守该协议
4.下载任务的创建
NSURLSessionDownloadTask
5.NSURLSessionDownloadDelegate
6.沙盒路径的获取
7.cache路径的获取及里面文件名的创建
*/
1.进行UI界面布局 用StoryBoard加载
一个Button,进度条,子类化的view显示进度的更新,view里面使用贝塞尔曲线画圆,并添加约束
2.定义全局的属性
@property (weak, nonatomic) IBOutlet MyProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIButton *btn;
@property (weak, nonatomic) IBOutlet UIProgressView *myProgressView;
@property (weak, nonatomic) IBOutlet UILabel *myProgressLabel;
//下载任务
@property(nonatomic,strong)NSURLSessionDownloadTask *task;
//记录上次暂停下载返回的记录
@property(nonatomic,strong)NSData *resumeData;
//创建下载任务属性
@property(nonatomic,strong)NSURLSession *session;
@end
.m的执行代码如下
//懒加载下载任务属性
- (NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *configuration=[NSURLSessionConfiguration defaultSessionConfiguration];
self.session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark--开始下载
- (void)start
{
//1.创建下载任务
NSURL *url=[NSURL URLWithString:@"
http://vfx.mtime.cn/Video/2015/07/04/mp4/150704102229172451_480.mp4
"];
self.task=[self.session downloadTaskWithURL:url];
//2.开始下载任务
[self.task resume];
}
#pragma mark---暂停下载
- (void)pause
{
//这里存在强引用嵌套,将self进行弱引用
/*
1.self对task进行了强引用,task 又对block 进行了引用,block又对self进行了引用,这就形成了循环引用
解决方法:对self 进行弱引用,__weak typedef(self)vc=self;
2.如果设置了实现和block,有实现了代理方法,程序优先执行block
*/
__weak typeof(self)vc=self;
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
vc.resumeData=resumeData;
vc.task=nil;
}];
}
#pragma mark---断点下载
- (void)resume
{
if (self.resumeData.length>0) {
self.task=[self.session downloadTaskWithResumeData:self.resumeData];
[self.task resume];
self.resumeData=nil;
}
}
- (IBAction)btnAct:(UIButton *)sender {
sender.selected=!sender.isSelected;
if (self.task==nil) {
if (self.resumeData) {
//断点续传
[self resume];
}
else{
//开始下载
[self start];
}
}
else
{
//暂停下载
[self pause];
}
}
#pragma mark---代理协议方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
//1.拿到cache文件夹的路径
NSString *cache=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
//2,拿到cache文件夹和文件名
NSString *file=[cache stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
//3.移动到下载好的文件到指定文件夹
NSFileManager *manager=[NSFileManager defaultManager];
[manager moveItemAtPath:location.path toPath:file error:nil];
}
//@optional
/* Sent periodically to notify the delegate of download progress. */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
self.progressView.progress=(double)totalBytesWritten/totalBytesExpectedToWrite;
//下载进度
NSString *text=[NSString stringWithFormat:@"%.2f%%",self.progressView.progress *100];
self.myProgressLabel.text=text;
}
/* Sent when a download has been resumed. If a download failed with an
* error, the -userInfo dictionary of the error will contain an
* NSURLSessionDownloadTaskResumeData key, whose value is the resume
* data.
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
@interface MyProgressView : UIView
//下载进度
@property (nonatomic, assign) float progress;
@end
@interface MyProgressView ()
@property (nonatomic, strong) UILabel *label;
@end
@implementation MyProgressView
- (UILabel *)label
{
if (_label == nil) {
_label = [[UILabel alloc] initWithFrame:self.bounds];
_label.textAlignment = NSTextAlignmentCenter;
[self addSubview:_label];
}
return _label;
}
-(void)setProgress:(float )progress
{
_progress = progress;
//设置显示的文字
self.label.text = [NSString stringWithFormat:@"%.2f%%",_progress * 100];
//调用 drawRect:
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
// Drawing code
//绘制弧线
//center -- 圆心
//radius -- 半径
//起始角度
//结束角度
//是否顺时针
//1.圆心
CGSize s = rect.size;
CGPoint center = CGPointMake(s.width * 0.5, s.height * 0.5);
//2.半径(取宽和高的小的)
CGFloat radius = (s.width > s.height) ? s.height * 0.5 : s.width * 0.5;
radius -= 10;
//3.起点
CGFloat sAngle = -M_PI_2;
//4.终点
CGFloat eAngle = self.progress * (2 * M_PI) + sAngle;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:sAngle endAngle:eAngle clockwise:YES];
[[UIColor yellowColor] set];//设置线条颜色
path.lineWidth = 10;
path.lineCapStyle = kCGLineCapRound;
[path stroke];
}
@end


利用NSURLSession下载视频,图片,能实现断点续传的更多相关文章
- 利用python下载视频
我们知道,有些网页上的视频,没有下载的按钮,并且有些视频需要付费下载,很多同学因此很苦恼.不怕,有问题找我,我试试用程序员的方式通俗易懂教会大家. 1.你先下载一个Python,不会下载的同学可以看这 ...
- 小白学Python(7)——利用Requests下载网页图片、视频
安装 Requests 如果安装了Requests就已经可用了,否则要安装 Requests,只要在你的CMD中运行这个简单命令即可: pip install requests requests使用 ...
- iOS开发——网络篇——NSURLSession,下载、上传代理方法,利用NSURLSession断点下载,AFN基本使用,网络检测,NSURLConnection补充
一.NSURLConnection补充 前面提到的NSURLConnection有些知识点需要补充 NSURLConnectionDataDelegate的代理方法有一下几个 - (void)conn ...
- Node.js mm131图片批量下载爬虫1.01 增加断点续传功能
这里的断点续传不是文件下载时的断点续传,而是指在爬行页面时有时会遇到各种网络中断而从中断前的页面及其数据继续爬行的过程,这个过程和断点续传原理上相似故以此命名.我的具体做法是:在下载出现故障或是图片已 ...
- C#利用开源软件ffMpeg截取视频图片
#region 从视频画面中截取一帧画面为图片 /// <summary> /// 从视频画面中截取一帧画面为图片 /// </summary> /// <param n ...
- 利用FFmpeg生成视频缩略图 2.1.6
利用FFmpeg生成视频缩略图 1.下载FFmpeg文件包,解压包里的\bin\下的文件解压到 D:\ffmpeg\ 目录下. 下载地址 http://ffmpeg.zeranoe.com/build ...
- C# 利用 OpenCV 进行视频捕获 (笔记)
原文:C# 利用 OpenCV 进行视频捕获 (笔记) 简介 这个项目是关于如何从网络摄像头或者视频文件(*.AVI)中捕获视频的,这个项目是用C#和OPENCV编写的. 这将有助于那些喜欢C#和Op ...
- Python3——根据m3u8下载视频(上)之urllib.request
干活干活,区区懒癌已经阻挡不了澎湃的洪荒之力了...... 运行环境:Windows基于python3.6 ---------------------------------------------- ...
- 使用图片视频展示插件blueimp Gallery改造网站的视频图片展示
在很多情况下,我们网站可能会展示我们的产品图片.以及教程视频等内容,结合一个比较好的图片.视频展示插件,能够使得我们的站点更加方便使用,也更加酷炫,在Github上有很多相关的处理插件可以找来使用,有 ...
随机推荐
- Spring MVC 的环境搭建和入门小程序
1.1.下载spring框架包. 1.1.1百度搜索Spring Framework. 进入spring官网,在网页右边选择想要下载的版本.如图 1.1.2进入页面按Ctrl+F搜索Distribut ...
- python抓取NBA现役球员基本信息数据
链接:http://china.nba.com/playerindex/ 所需获取JSON数据页面链接:http://china.nba.com/static/data/league/playerli ...
- Java设计和实现方法
方法签名 方法名是驼峰命名 方法名最好能说明该方法主要做什么 方法参数的名字最好能说明该参数的意义 方法参数个数最好低于6个 例如: public void setTitleVisible(int l ...
- gulp+browser-sync使用方法
gulp简介 gulp是基于流的自动化构建工具,也就是说gulp是通过操作流实现自动编译,压缩文件等操作的.这得益于node.js对流的支持,当然gulp.js和构建的任务文件都是JavaScript ...
- android学习9——Handler简单用法
Handler用来发消息和处理消息.典型的用法是更新界面.android不允许在子线程里面更新界面,通常是把Handler传到子线程中,在子线程里通过sendEmptyMessage函数发消息.Han ...
- 深入了解Unity中LineRenderer与TrailRenderer
LineRender和TrailRender是两个好东西,很多Unity拖尾特效都会使用到它们.一些简单的介绍可以参见官方的API文档.在这里探讨一下它们具体的渲染方式,而后给出一些Shader以便更 ...
- 【CNMP系列】CentOS7.0下安装MySql5.6服务
接上一回的话,CentOS7.0下安装好了Nginx服务,对于我们的CNMP,我们可以开始我们的M啦,就是传统意义上的MySql服务 MySql简介 MySQL是一个关系型数据库管理系统,由瑞典MyS ...
- css4激动人心的新特性及浏览器支持度
CSS3的选择器提供了很多像:nth-child这样有用的选择器,并且得到浏览器支持.CSS的第四代 选择器CSS4选择器),经我们带来了更多有用的选择器. 1.否定伪类:not 否定伪类选择器其实在 ...
- java中 i = i++ 的结果
昨天看到下面这段代码,分享出来给大家看看,大家也可以讨论讨论. int i = 0; i = i++; System.out.println("i的值是 "+i); 根据我们通常所 ...
- Java系统属性与Preferences API的简单介绍
系统属性在和Preferences API都是键值对,前者只能当前应用程序中共享数据,而后者可以在用户的各个应用或用户之间共享数据. 系统属性 Java 的系统属性决定了 Java 程序实际运行的环境 ...