#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
网络:NSURLSession 的断点续传
最新推荐文章于 2022-03-16 09:29:24 发布