#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (nonatomic, strong) NSURLSession *session;
- (IBAction)download:(UIButton *)sender;
@end
@implementation ViewController
- (NSURLSession *)session
{
if (!_session) {
// 获得session
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)download:(UIButton *)sender {
// 按钮状态取反
sender.selected = !sender.isSelected;
if (self.task == nil) {
if (self.resumeData) { // 恢复
[self resume];
} else {
[self start]; // 开始
}
} else {
[self resume];
}
}
// 从零开始
- (void)start
{
// 1. 创建一个任务
NSURL *url = [NSURL URLWithString:@""];
self.task = [self.session downloadTaskWithURL:url];// 如果用block就会优先调用block
// 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 * _Nullable resumeData) {
// resumeData : 包含了继续下载的开始位置
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];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
// 获得下载进度
self.progressView.progress = (double)totalBytesExpectedToWrite / totalBytesWritten;
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
@end
NSURLSession断点续传
最新推荐文章于 2022-03-16 09:29:24 发布