<h2>断点续传原理:
1.断点:记录点击暂停时已经下载的字节数
2.续传:将上次记录的字节数通过HTTP请求头传给服务器,继续下载
</h2>
具体实现:
系统自带的NSURLSessionDownloadTask非常的简单
创建属性
@property(nonatomic, strong) NSURLSessionDownloadTask * task;
@property(nonatomic, strong) NSURLSession * session;
@property(nonatomic, strong) NSData * summate;
// 将player写入属性,用模拟器start项目时必须用属性,否则是没有声音的
@property(nonatomic, strong) AVAudioPlayer * player;
P.s: player为了实现最后下载完音乐资源的播放
先初始化session
写的比较懒,见谅
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
遵守代理
@interface ViewController ()<NSURLSessionDownloadDelegate>
开始下载&继续下载
- (IBAction)StartWork:(id)sender {
if (self.task) {
NSLog(@"继续下载");
NSLog(@"%lu",(unsigned long)self.sumaDate.length);
self.task = [self.session downloadTaskWithResumeData:self.sumaDate];
} else {
NSLog(@"开始下载");
self.task= [self.session downloadTaskWithURL:[NSURL URLWithString:@"http://yinyueshiting.baidu.com/data2/music/244383700/244379959144425526164.mp3?xcode=ee4c4a527b584e3a794b86d808232fc4"]];
}
[self.task resume];
}
暂停下载
- (IBAction)PauseWork:(id)sender {
NSLog(@"暂停下载");
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
NSLog(@"%lu",(unsigned long)resumeData.length);
self.sumaDate = [NSData dataWithData:resumeData];
}];
}
实现主要的两个代理方法
#pragma NSURLSessionDownloadDelegate
// 完成下载(实现音乐播放)
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSLog(@"已下载");
NSURL * url=[NSURL fileURLWithPath:@"/Users/apple/Desktop/music.mp3"];
NSFileManager * manager=[NSFileManager defaultManager];
[manager moveItemAtURL:location toURL:url error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
NSData * data=[manager contentsAtPath:@"/Users/apple/Desktop/music.mp3"];
self.player = [[AVAudioPlayer alloc] initWithData:data error:nil];
[self.player play];
});
}
// 监听下载时的状态
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
double downloadProgress = totalBytesWritten / (double)totalBytesExpectedToWrite;
NSLog(@"%f",downloadProgress);
}