#import "ViewController.h"
#define FileName @"121212.mp4" @interface ViewController ()<NSURLSessionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *proessView;
/** 接受响应体信息 */
@property (nonatomic, strong) NSFileHandle *handle;
@property (nonatomic, assign) NSInteger totalSize;
@property (nonatomic, assign) NSInteger currentSize;
@property (nonatomic, strong) NSString *fullPath;
@property (nonatomic, strong) NSURLSessionDataTask *dataTask;
@property (nonatomic, strong) NSURLSession *session; @end @implementation ViewController -(void)viewDidLoad
{
[super viewDidLoad]; //1.读取保存的文件总大小的数据,0
//2.获得当前已经下载的数据的大小
//3.计算得到进度信息 }
-(NSString *)fullPath
{
if (_fullPath == nil) { //获得文件全路径
_fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:FileName];
}
return _fullPath;
} -(NSURLSession *)session
{
if (_session == nil) {
//3.创建会话对象,设置代理
/*
第一个参数:配置信息 [NSURLSessionConfiguration defaultSessionConfiguration]
第二个参数:代理
第三个参数:设置代理方法在哪个线程中调用
*/
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
-(NSURLSessionDataTask *)dataTask
{
if (_dataTask == nil) {
//1.url
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]; //2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //3 设置请求头信息,告诉服务器请求那一部分数据
self.currentSize = [self getFileSize];
NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentSize];
[request setValue:range forHTTPHeaderField:@"Range"]; //4.创建Task
_dataTask = [self.session dataTaskWithRequest:request];
}
return _dataTask;
} -(NSInteger)getFileSize
{
//获得指定文件路径对应文件的数据大小
NSDictionary *fileInfoDict = [[NSFileManager defaultManager]attributesOfItemAtPath:self.fullPath error:nil];
NSLog(@"%@",fileInfoDict);
NSInteger currentSize = [fileInfoDict[@"NSFileSize"] integerValue]; return currentSize;
}
- (IBAction)startBtnClick:(id)sender
{
[self.dataTask resume];
} - (IBAction)suspendBtnClick:(id)sender
{
NSLog(@"_________________________suspend");
[self.dataTask suspend];
} //注意:dataTask的取消是不可以恢复的
- (IBAction)cancelBtnClick:(id)sender
{
NSLog(@"_________________________cancel");
[self.dataTask cancel];
self.dataTask = nil;
} - (IBAction)goOnBtnClick:(id)sender
{
NSLog(@"_________________________resume");
[self.dataTask resume];
} #pragma mark ----------------------
#pragma mark NSURLSessionDataDelegate
/**
* 1.接收到服务器的响应 它默认会取消该请求
*
* @param session 会话对象
* @param dataTask 请求任务
* @param response 响应头信息
* @param completionHandler 回调 传给系统
*/
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
//获得文件的总大小
//expectedContentLength 本次请求的数据大小
self.totalSize = response.expectedContentLength + self.currentSize; if (self.currentSize == ) {
//创建空的文件
[[NSFileManager defaultManager]createFileAtPath:self.fullPath contents:nil attributes:nil]; }
//创建文件句柄
self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath]; //移动指针
[self.handle seekToEndOfFile]; /*
NSURLSessionResponseCancel = 0,取消 默认
NSURLSessionResponseAllow = 1, 接收
NSURLSessionResponseBecomeDownload = 2, 变成下载任务
NSURLSessionResponseBecomeStream 变成流
*/
completionHandler(NSURLSessionResponseAllow);
} /**
* 接收到服务器返回的数据 调用多次
*
* @param session 会话对象
* @param dataTask 请求任务
* @param data 本次下载的数据
*/
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{ //写入数据到文件
[self.handle writeData:data]; //计算文件的下载进度
self.currentSize += data.length;
NSLog(@"%f",1.0 * self.currentSize / self.totalSize); self.proessView.progress = 1.0 * self.currentSize / self.totalSize;
} /**
* 请求结束或者是失败的时候调用
*
* @param session 会话对象
* @param dataTask 请求任务
* @param error 错误信息
*/
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%@",self.fullPath); //关闭文件句柄
[self.handle closeFile];
self.handle = nil;
} -(void)dealloc
{
//清理工作
//finishTasksAndInvalidate
[self.session invalidateAndCancel];
} @end

#####6 使用NSURLSessionDataTask实现大文件离线断点下载(完整)

(1)关于NSOutputStream的使用

```objc

//1. 创建一个输入流,数据追加到文件的屁股上

//把数据写入到指定的文件地址,如果当前文件不存在,则会自动创建

NSOutputStream *stream = [[NSOutputStream alloc]initWithURL:[NSURL fileURLWithPath:[self fullPath]] append:YES];

//2. 打开流

[stream open];

//3. 写入流数据

[stream write:data.bytes maxLength:data.length];

//4.当不需要的时候应该关闭流

[stream close];

```

(2)关于网络请求请求头的设置(可以设置请求下载文件的某一部分)

```objc

//1. 设置请求对象

//1.1 创建请求路径

NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];

//1.2 创建可变请求对象

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//1.3 拿到当前文件的残留数据大小

self.currentContentLength = [self FileSize];

//1.4 告诉服务器从哪个地方开始下载文件数据

NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentContentLength];

NSLog(@"%@",range);

//1.5 设置请求头

[request setValue:range forHTTPHeaderField:@"Range"];

```

(3)NSURLSession对象的释放

```objc

-(void)dealloc

{

//在最后的时候应该把session释放,以免造成内存泄露

//    NSURLSession设置过代理后,需要在最后(比如控制器销毁的时候)调用session的invalidateAndCancel或者resetWithCompletionHandler,才不会有内存泄露

//    [self.session invalidateAndCancel];

[self.session resetWithCompletionHandler:^{

NSLog(@"释放---");

}];

}

```

(4)优化部分

01 关于文件下载进度的实时更新

02 方法的独立与抽取

---

ios开发网络学习十一:NSURLSessionDataTask离线断点下载(断点续传)的更多相关文章

  1. ios开发网络学习四:NSURLConnection大文件断点下载

    #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...

  2. ios开发网络学习九:NSURLSessionDownloadTask实现大文件下载

    一:NSURLSessionDownloadTask:实现文件下载:无法监听进度 #import "ViewController.h" @interface ViewControl ...

  3. ios开发网络学习AFN框架的使用一:get和post请求

    #import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...

  4. ios开发网络学习:一:NSURLConnection发送GET,POST请求

    #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...

  5. ios开发网络学习AFN三:AFN的序列化

    #import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...

  6. ios开发网络学习十二:NSURLSession实现文件上传

    #import "ViewController.h" // ----WebKitFormBoundaryvMI3CAV0sGUtL8tr #define Kboundary @&q ...

  7. ios开发网络学习十:利用文件句柄实现大文件下载

    #import "ViewController.h" @interface ViewController ()<NSURLSessionDataDelegate> @p ...

  8. iOS开发网络学习七:NSURLSession的基本使用get和post请求

    #import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...

  9. ios开发网络学习六:设置队列请求与RunLoop

    #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...

随机推荐

  1. JQuery DataTables 列自己定义数据类型排序

    使用JQ DataTables 的时候.希望某列数据能够进行自己定义排序.操作例如以下:(以中文排序和百分比排序为例) 1:定义排序类型: //百分率排序 jQuery.fn.dataTableExt ...

  2. 火狐—火狐浏览器中的“HttpWatch”

    在IE下通过HttpWatch能够查看HTTP请求的相关细节.这对我们分析程序的运行效率很有帮助,但是在火狐浏览器中的难道就没有相似的工具了吗?答案是否定的--火狐浏览器中也有.在火狐浏览器中该工具叫 ...

  3. Leetcode:signal_number_ii

    一.     题目 给一个数组,当中仅仅有一个数出现一次.其它的数都出现3次,请找出这个数.要求时间复杂度是O(n).空间复杂度O(1). 二.     分析 第一次遇见这种题,真心没思路-.前面的s ...

  4. 内网使用 IPV6 之Teredo篇

    这篇转载自 http://bbs.pcbeta.com/viewthread-1580771-1-1.html 上IPv6站点之Teredo篇http://bbs.pcbeta.com/viewthr ...

  5. UVA 11488 Hyper Prefix Sets (字典树)

    https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  6. JS实践与写博客-序

    大二的时候,就开始接触JavaScript了. 当时学了1年多,主要是认真看了一本JavaScript的入门书籍,了解了JavaScript大致怎么回事.在独自做Web项目的时候,用的都是JavaSc ...

  7. C#与C++ DLL的交互

    C#与C++交互,总体来说可以有两种方法: 1.利用C++/CLI作为代理中间层 2.利用PInvoke实现直接调用   第一种方法:实现起来比较简单直观,并且可以实现C#调用C++所写的类,但是问题 ...

  8. hiho 1182 : 欧拉路&#183;三

    1182 : 欧拉路·三 这时题目中给的提示: 小Ho:是这种.每次转动一个区域不是相当于原来数字去掉最左边一位,并在最后加上1或者0么. 于是我考虑对于"XYYY",它转动之后能 ...

  9. ActivityChooserView-如何隐藏选择的应用图标

    今天在修改一个问题的时候,用到了ActivityChooserView类,但是,这个类会自动显示两个按钮,一个是点击有下拉框的,一个是选择应用以后,显示应用图标的.因为应用图标跟当时的环境非常的不搭, ...

  10. Android LruCache类分析

    public class LurCache<K, V> { private final LinkedHashMap<K, V> map; private int size; / ...