iOS开发-实现大文件下载与断点下载思路

 更新时间:2017年01月14日 14:20:48   作者:Jierism  
本篇文章主要介绍了iOS开发-实现大文件下载与断点下载思路,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

大文件下载

方案一:利用NSURLConnection和它的代理方法,及NSFileHandle(iOS9后不建议使用)

相关变量:

 @property (nonatomic,strong) NSFileHandle *writeHandle;
@property (nonatomic,assign) long long totalLength; 

1>发送请求

// 创建一个请求
  NSURL *url = [NSURL URLWithString:@""];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  // 使用NSURLConnection发起一个异步请求
  [NSURLConnection connectionWithRequest:request delegate:self]; 

2>在代理方法中处理服务器返回的数据

/** 在接收到服务器的响应时调用下面这个代理方法
  1.创建一个空文件
  2.用一个句柄对象关联这个空文件,目的是方便在空文件后面写入数据
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
  // 创建文件路径
  NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
  NSString *filePath = [caches stringByAppendingPathComponent:@"videos.zip"];
  
  // 创建一个空的文件到沙盒中
  NSFileManager *mgr = [NSFileManager defaultManager];
  [mgr createFileAtPath:filePath contents:nil attributes:nil];
  
  // 创建一个用来写数据的文件句柄
  self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  
  // 获得文件的总大小
  self.totalLength = response.expectedContentLength;
}

/** 在接收到服务器返回的文件数据时调用下面这个代理方法
  利用句柄对象往文件的最后面追加数据
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
  // 移动到文件的最后面
  [self.writeHandle seekToEndOfFile];
  
  // 将数据写入沙盒
  [self.writeHandle writeData:data];
}

/**
  在所有数据接收完毕时,关闭句柄对象
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  // 关闭文件并清空
  [self.writeHandle closeFile];
  self.writeHandle = nil;
} 

方案二:使用NSURLSession的NSURLSessionDownloadTask和NSFileManager

NSURLSession *session = [NSURLSession sharedSession];
  NSURL *url = [NSURL URLWithString:@""];
  // 可以用来下载大文件,数据将会存在沙盒里的tmp文件夹
  NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    // location :临时文件存放的路径(下载好的文件)
    
    // 创建存储文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    // response.suggestedFilename:建议使用的文件名,一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
    
    /**将临时文件剪切或者复制到Caches文件夹
     AtPath :剪切前的文件路径
     toPath :剪切后的文件路径
     */
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr moveItemAtPath:location.path toPath:file error:nil];
  }];
  [task resume]; 

方案三:使用NSURLSessionDownloadDelegate的代理方法和NSFileManger

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
  // 创建一个下载任务并设置代理
  NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
  NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  
  NSURL *url = [NSURL URLWithString:@""];
  NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
  [task resume];
}

#pragma mark - 
/**
  下载完毕后调用
  参数:lication 临时文件的路径(下载好的文件)
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
  // 创建存储文件路径
  NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
  // response.suggestedFilename:建议使用的文件名,一般跟服务器端的文件名一致
  NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
  
  /**将临时文件剪切或者复制到Caches文件夹
   AtPath :剪切前的文件路径
   toPath :剪切后的文件路径
   */
  NSFileManager *mgr = [NSFileManager defaultManager];
  [mgr moveItemAtPath:location.path toPath:file error:nil];
}

/**
  每当下载完一部分时就会调用(可能会被调用多次)
  参数:
    bytesWritten 这次调用下载了多少
    totalBytesWritten 累计写了多少长度到沙盒中了
    totalBytesExpectedToWrite 文件总大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
   didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
  // 这里可以做些显示进度等操作
}

/**
  恢复下载时使用
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
  // 用于断点续传
} 

断点下载

方案一:

1>在方案一的基础上新增两个变量和按扭

@property (nonatomic,assign) long long currentLength;
@property (nonatomic,strong) NSURLConnection *conn; 

2>在接收到服务器返回数据的代理方法中添加如下代码

  // 记录断点,累计文件长度
  self.currentLength += data.length; 

3>点击按钮开始(继续)或暂停下载

- (IBAction)download:(UIButton *)sender {
  
  sender.selected = !sender.isSelected;
  
  if (sender.selected) { // 继续(开始)下载
    NSURL *url = [NSURL URLWithString:@""];
    // ****关键点是使用NSMutableURLRequest,设置请求头Range
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    
    NSString *range = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
    [mRequest setValue:range forHTTPHeaderField:@"Range"];
    
    // 下载
    self.conn = [NSURLConnection connectionWithRequest:mRequest delegate:self];
  }else{
    [self.conn cancel];
    self.conn = nil;
  }
} 

4>在接受到服务器响应执行的代理方法中第一行添加下面代码,防止重复创建空文件

 if (self.currentLength) return; 

方案二:使用NSURLSessionDownloadDelegate的代理方法

所需变量

 @property (nonatomic,strong) NSURLSession *session;
@property (nonatomic,strong) NSData *resumeData; //包含了继续下载的开始位置和下载的url
@property (nonatomic,strong) NSURLSessionDownloadTask *task; 

方法

// 懒加载session
- (NSURLSession *)session
{
  if (!_session) {
    NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  }
  return _session;
}

- (IBAction)download:(UIButton *)sender {
  
  sender.selected = !sender.isSelected;
  if (self.task == nil) { // 开始(继续)下载
    if (self.resumeData) { // 原先有数据则恢复
      [self resume];
    }else{
      [self start]; // 原先没有数据则开始
    }
  }else{ // 暂停
    [self pause];
  }
}

// 从零开始
- (void)start{
  NSURL *url = [NSURL URLWithString:@""];
  self.task = [self.session downloadTaskWithURL:url];
  [self.task resume];
}

// 暂停
- (void)pause{
  __weak typeof(self) vc = self;
  [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
    //resumeData : 包含了继续下载的开始位置和下载的url
    vc.resumeData = resumeData;
    vc.task = nil;
  }];
}

// 恢复
- (void)resume{
  // 传入上次暂停下载返回的数据,就可以回复下载
  self.task = [self.session downloadTaskWithResumeData:self.resumeData];
  // 开始任务
  [self.task resume];
  // 清空
  self.resumeData = nil;
}

#pragma mark - NSURLSessionDownloadDelegate
/**
  下载完毕后调用
  参数:lication 临时文件的路径(下载好的文件)
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
  // 创建存储文件路径
  NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
  // response.suggestedFilename:建议使用的文件名,一般跟服务器端的文件名一致
  NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
  
  /**将临时文件剪切或者复制到Caches文件夹
   AtPath :剪切前的文件路径
   toPath :剪切后的文件路径
   */
  NSFileManager *mgr = [NSFileManager defaultManager];
  [mgr moveItemAtPath:location.path toPath:file error:nil];
}

/**
  每当下载完一部分时就会调用(可能会被调用多次)
  参数:
    bytesWritten 这次调用下载了多少
    totalBytesWritten 累计写了多少长度到沙盒中了
    totalBytesExpectedToWrite 文件总大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
   didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
  // 这里可以做些显示进度等操作
}

/**
  恢复下载时使用
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 详解IOS的Automatically Sign在设备上打包

    详解IOS的Automatically Sign在设备上打包

    本篇教程主要给大家分享了IOS的Automatically Sign如何在设备上直接打包,有需要的朋友参考学习下。
    2018-01-01
  • iOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下
    2016-09-09
  • 详解iOS学习笔记(十七)——文件操作(NSFileManager)

    详解iOS学习笔记(十七)——文件操作(NSFileManager)

    这篇文章主要介绍了详解iOS学习笔记(十七)——文件操作(NSFileManager),具有一定的参考价值,有需要的可以了解一下。
    2016-12-12
  • iOS微信浏览器回退不刷新实例(监听浏览器回退事件)

    iOS微信浏览器回退不刷新实例(监听浏览器回退事件)

    下面小编就为大家带来一篇iOS微信浏览器回退不刷新实例(监听浏览器回退事件)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • NSString属性何时用strong何时用copy?

    NSString属性何时用strong何时用copy?

    相信各位iOS开发者们都考虑过这个问题,平时写NSString的属性时都用copy,那strong要何时用呢?下面这篇文章就来看一下什么时候应该用copy,什么时候应该用strong。有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-12-12
  • IOS开发之路--C语言基础知识

    IOS开发之路--C语言基础知识

    当前移动开发的趋势已经势不可挡,这个系列希望浅谈一下个人对IOS开发的一些见解,今天我们从最基础的C语言开始,C语言部分我将分成几个章节去说,今天我们简单看一下C的一些基础知识,更高级的内容我将放到后面的文章中。
    2014-08-08
  • iOS超出父控件范围无法点击问题解决

    iOS超出父控件范围无法点击问题解决

    这篇文章主要介绍了iOS超出父控件范围无法点击问题解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • IOS第三方库ZXEasyCoding

    IOS第三方库ZXEasyCoding

    本文给大家简单介绍了object-c的第三方库ZXEasyCoding的安装、示例以及github地址,有需要的小伙伴可以参考下
    2016-11-11
  • 详解 iOS 系统中的视图动画

    详解 iOS 系统中的视图动画

    这篇文章主要介绍了iOS 系统中的视图动画的的相关资料,帮助大家更好的理解和学习使用ios开发,感兴趣的朋友可以了解下
    2021-02-02
  • iOS Runtime详解(新手也看得懂)

    iOS Runtime详解(新手也看得懂)

    这篇文章主要给大家介绍了关于iOS Runtime的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-02-02

最新评论