通过NSURLSessionDownloadTask代理实现下载大文件
2016-04-17 16:18
411 查看
// // ViewController.m // NSURLSessionDownloadTask // // Created by hq on 16/4/17. // Copyright © 2016年 hanqing. All rights reserved. // #import "ViewController.h" @interface ViewController () <NSURLSessionDownloadDelegate> @property (weak, nonatomic) IBOutlet UIButton *startBut; @property (weak, nonatomic) IBOutlet UIProgressView *pro; - (IBAction)startDownload:(UIButton *)sender; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (IBAction)startDownload:(UIButton *)sender { NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]]; NSString *urlString=@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"; NSURLSessionDownloadTask *task=[session downloadTaskWithURL:[NSURL URLWithString:urlString]]; //恢复下载任务 [task resume]; self.startBut.enabled=NO; } -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ NSLog(@"已下载%lld",totalBytesWritten); NSLog(@"文件总大小%lld",totalBytesExpectedToWrite); //self.pro.progress=(1.0*totalBytesWritten/totalBytesExpectedToWrite); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //必须放在主线程当中才回更新进度条----------------------------- self.pro.progress=(1.0*totalBytesWritten/totalBytesExpectedToWrite); }]; } -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ //NSLog(@"%@",location); //下载完成,将文件剪切到我们的cache文件夹当中去 NSString *cachePath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject; NSString *fileName=[cachePath stringByAppendingPathComponent:@"video.mp4"]; NSFileManager *fileManager=[NSFileManager defaultManager]; [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:fileName] error:nil]; NSLog(@"%@",fileName); } //不管下载成功还是失败,都会来到该方法,不过下载失败的话,error有值,下载成功error为null -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ if (error) { NSLog(@"下载失败了%@",error); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
相关文章推荐
- MyBaits传递多个参数
- Django 老司机
- android聊天器(仿QQ)编写第一天__界面的搭建和主要的布局
- JQuery绑定事件与移除事件、动画
- js 实现图片位置随意变化
- JAVA IO(三)
- linux中help的用法
- Android Studio 2.0新特性之Instant Run
- iOS开发-FMDB
- 四个100以内的随机数排大小
- 第五周项目二(1)-游戏中的角色类
- MFC程序在XP系统上崩溃
- 利用最小堆管理事件超时
- Exchange 2016集成ADRMS系列-5:集成Exchange 2016
- local variable XXX referenced before assignment
- LeetCode——045
- java之FileReader与FileWriter
- hdu-5667 Sequence(矩阵快速幂+费马小定理+快速幂)
- 缓存
- 字符串编辑距离(Levenshtein距离)算法