码迷,mamicode.com
首页 > Web开发 > 详细

利用NSURLSession下载视频,图片,能实现断点续传

时间:2015-11-16 00:38:17      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

首先分析下载资源到本地,就得有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.定义全局的属性

 @interface ViewController ()<NSURLSessionDownloadDelegate>
@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的执行代码如下

 @implementation ViewController
//懒加载下载任务属性
- (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
{
 
//这里子类化的view 里面加载贝塞尔曲线,用匿名的类目加一个属性label,显示进度值,下面会子类化出view
    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
 
 
 
//3.子类化的view显示进度值和条
.h文件增加进度属性
 #import <UIKit/UIKit.h>

@interface MyProgressView : UIView
//下载进度
@property (nonatomic, assign) float progress;

@end
 
.m进度控件的实现文件
 #import "MyProgressView.h"

@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
这样就实现断点下载,续传功能
UI界面比较丑,基本功能已实现,一些美化图片自己美化,可以加背景图片设置更好的交互方式
截图如下
 
技术分享技术分享

利用NSURLSession下载视频,图片,能实现断点续传

标签:

原文地址:http://www.cnblogs.com/tryFighting/p/4967842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!