NSURLSession实现断点下载

NSURLSession实现断点下载

@interface HMViewController () <NSURLSessionDownloadDelegate, NSURLSessionDataDelegate]]>

@property ( weak , nonatomic ) IBOutlet UIProgressView *progressView;
- (
IBAction )download:( UIButton *)sender;

@property ( nonatomic , strong ) NSURLSessionDownloadTask *task;
@property ( nonatomic , strong ) NSData *resumeData;
@property ( nonatomic , strong ) NSURLSession *session;
@end

@implementation HMViewController

- (
NSURLSession *)session
{
   
if (! _session ) {
       
// 获得 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
{
   
// 1. 创建一个下载任务
   
NSURL *url = [ NSURL URLWithString : @"http://192.168.15.172:8080/MJServer/resources/videos/minion_01.mp4" ];
   
self . task = [ self . session downloadTaskWithURL :url];
   
   
// 2. 开始任务
    [
self . task resume ];
}

/**
 * 
恢复(继续)
 */

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

/**
 * 
暂停
 */

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

#pragma mark - NSURLSessionDownloadDelegate
- ( 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 文件夹
   
NSFileManager *mgr = [ NSFileManager defaultManager ];
   
   
// AtPath : 剪切前的文件路径
   
// ToPath : 剪切后的文件路径
    [mgr
moveItemAtPath :location. path toPath :file error : nil ];
}

- (
void )URLSession:( NSURLSession *)session downloadTask:( NSURLSessionDownloadTask *)downloadTask
      didWriteData:(
int64_t )bytesWritten
 totalBytesWritten:(
int64_t )totalBytesWritten
totalBytesExpectedToWrite:(
int64_t )totalBytesExpectedToWrite
{
   
NSLog ( @" 获得下载进度 --%@" , [NSThread currentThread ]);
   
// 获得下载进度
   
self . progressView . progress = ( double )totalBytesWritten / totalBytesExpectedToWrite;
}

- (
void )URLSession:( NSURLSession *)session downloadTask:( NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(
int64_t )fileOffset
expectedTotalBytes:(
int64_t )expectedTotalBytes
{
   
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值