断点续传原理:
断点:在点击暂停按钮或者断网的时候记录已经下载的字节数
续传:在点击开始按钮的时候或者监听到网络重连的时候将上次记录的字节数通过HTTP请求传给服务器,继续下载
- 拖两个按钮
- 连接方法
#pragma mark - 开始
- (IBAction)startAction:(id)sender {
}
#pragma mark - 暂停
- (IBAction)stopAction:(id)sender {
}```
- 声明属性
import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask; // 下载任务
@property (nonatomic, strong) NSURLSession *session; // 网络
@property (nonatomic, strong) NSData *downloadData; // 下载的数据
@property(nonatomic, strong) AVAudioPlayer * player; // 将player写入属性,用模拟器start项目时必须用属性,否则是没有声音的 player是为了下载完成后播放音乐
@end```
- 遵守下载代理
- 初始化网络
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}```
- 开始下载
pragma mark - 开始
-
// 开始任务
[self.downloadTask resume];
}``` -
暂停下载
#pragma mark - 暂停
- (IBAction)stopAction:(id)sender {
NSLog(@"暂停下载");
[self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
// 把暂停下载的时候的数据存储到全局变量中
NSLog(@"%lu", resumeData.length);
self.downloadData = resumeData;
}];
}```
- 下载完成实现音乐播放
pragma mark - 完成下载实现音乐播放
-
(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSLog(@"已下载");// 存储到本地
NSURL * url=[NSURL fileURLWithPath:@"/Users/jiayuanfa/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/jiayuanfa/Desktop/music.mp3"];
self.player = [[AVAudioPlayer alloc] initWithData:data error:nil];
[self.player play];
});
}``` -
监听下载进度
#pragma mark - 监听下载 进度条等等
- (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);
}```
- 运行
点击开始按钮
点击暂停按钮然后再点击开始按钮
下载完成
桌面保存