网络:NSURLSession 的断点续传

#import "ViewController.h"
#import "SSZipArchive.h"
#import "NSString+Hash.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (nonatomic, strong) NSURLSession *session; // 自定义会话
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask; // 下载任务
@property (nonatomic, strong) NSData *resumeData; // 断点续传的数据
@property (nonatomic, strong) NSURL *url;
 @end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"-----%@",NSHomeDirectory());


}

// 在暂停或者继续之前先判断当前的任务状态
- (IBAction)pause:(id)sender {
    // 只有在运行状态的才能暂停
    if (self.downloadTask.state == NSURLSessionTaskStateRunning) {
        NSLog(@"暂停");
//        [self.downloadTask suspend];

        [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            [resumeData writeToFile:[self resumeDataPathWithURL:self.url] atomically:YES];
        }];
    }

}

- (IBAction)resume:(id)sender {
//    if (self.downloadTask.state == NSURLSessionTaskStateSuspended) {
//        [self loadResumeDataWithURL:self.url];
//        [self loadData];
//    }
    if (self.downloadTask.state==NSURLSessionTaskStateCanceling||self.downloadTask.state == NSURLSessionTaskStateSuspended) {
        [self loadData];

    }


}


//通过url得到resumeData的保存路径---用md5改变路径,降低重复率
- (NSString *)resumeDataPathWithURL:(NSURL *)url {
    NSString *doc = NSTemporaryDirectory();

    // 60*60.png
    // 文件名
    NSString *fileName = [url.path.lastPathComponent.md5String stringByAppendingString:@"~resume"];

    return [doc stringByAppendingPathComponent:fileName];
}

//把属性中resumeData数据根据url保存到指定路径
- (void)loadResumeDataWithURL:(NSURL *)url {
    // 续传数据的路径
    NSString *filePath = [self resumeDataPathWithURL:url];

    self.resumeData = [NSData dataWithContentsOfFile:filePath];
    // 删除原文件
    NSFileManager *manager = [NSFileManager defaultManager];

    [manager removeItemAtPath:filePath error:NULL];
}


// 使用NSURLSession 下载,内存锋值不高。但是有些Xcode版本,峰值很6.3以前
// 但是在真机上不存在这个问题
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [self loadData];
}

- (void)loadData {

//    NSURL *url = [NSURL URLWithString:@"http://dlsw.baidu.com/sw-search-sp/soft/c6/25790/WeChatzhCN1.0.0.6.1428545414.dmg"];
        NSURL *url = [NSURL URLWithString:@"http://localhost/ui.mp4"];

    self.url = url;

    // 在下载之前,先读取续传数据
    [self loadResumeDataWithURL:url];

    if (self.resumeData) {
        NSLog(@"断点续传");
        // 断点续传的数据来创建
        self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
    }else {
        // 下载任务 URL 或者 NSURLRequest
        self.downloadTask = [self.session downloadTaskWithURL:url];

    }
    // 继续(开始)下载
    [self.downloadTask resume];
}

#pragma mark - Session 的代理
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    //    NSLog(@"%@",location);
    NSLog(@"下载完成,开始移动文件");
    // 处理下载完成的文件
    //    NSFileManager *manager = [NSFileManager defaultManager];
    //    // 保存文件的路径
    //    NSString *fileName = @"123.mp4";
    //    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:fileName];
    //
    //    // 把临时文件移动到缓存目录,并且改成我们需要的后缀名
    //    // 使用复制或者移动都可以
    //    //        [manager moveItemAtPath:location.path toPath:path error:NULL];
    //    [manager copyItemAtPath:location.path toPath:path error:NULL];
}

// 此方法并没什么卵用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {
    NSLog(@"didResumeAtOffset");
}

/**
 session 会话
 downloadTask 任务的对象
 bytesWritten 本次写入的数据长度
 totalBytesWritten 总共接收了数据长度
 totalBytesExpectedToWrite 总的数据长度
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    CGFloat progress = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite;
    NSLog(@"%f - %@",progress,[NSThread currentThread]);

    // 回调在子线程,所以我们需要回到主线程刷新UI
    //    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
    //        self.progressView.progress = progress;
    //    }];
    //
    // 如果使用异步,下载会继续。但是刷新界面会等待主线程有空闲的时候
    dispatch_async(dispatch_get_main_queue(), ^{
        self.progressView.progress = progress;
    });
}




- (NSURLSession *)session {
    if (_session == nil) {
        // 创建配置对象 通常使用默认的配置就可以了
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        /*
         delegateQueue
         如果设置nil , 代理在子线程回调,串行队列
         [[NSOperationQueue alloc]init] 还是在同一时间内只开启一条线程
         [NSOperationQueue mainQueue] 在主线程回调
         */
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}

@end
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值