<h2>斷點續(xù)傳原理:
1.斷點:記錄點擊暫停時已經(jīng)下載的字節(jié)數(shù)
2.續(xù)傳:將上次記錄的字節(jié)數(shù)通過HTTP請求頭傳給服務(wù)器姿鸿,繼續(xù)下載
</h2>
具體實現(xiàn):
系統(tǒng)自帶的NSURLSessionDownloadTask非常的簡單
創(chuàng)建屬性
@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為了實現(xiàn)最后下載完音樂資源的播放
先初始化session
寫的比較懶般妙,見諒
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
遵守代理
@interface ViewController ()<NSURLSessionDownloadDelegate>
開始下載&繼續(xù)下載
- (IBAction)StartWork:(id)sender {
if (self.task) {
NSLog(@"繼續(xù)下載");
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];
}];
}
實現(xiàn)主要的兩個代理方法
#pragma NSURLSessionDownloadDelegate
// 完成下載(實現(xiàn)音樂播放)
- (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];
});
}
// 監(jiān)聽下載時的狀態(tài)
- (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);
}