實現(xiàn)數(shù)據(jù)的離線緩存甫菠,當(dāng)在建立起數(shù)據(jù)請求的時候蹦疑,根據(jù)url生成一個文件路徑蚓挤,讓數(shù)據(jù)下載到一個臨時的文件路徑下商源。
- 第一種情況:當(dāng)請求發(fā)起時一直下載到下載成功车份,這時候就將該文件移動到緩存目錄下緩存起來。
- 第二種情況:當(dāng)中斷下載數(shù)據(jù)時牡彻,對該臨時文件不做任何處理扫沼,然后再次播放該視頻請求數(shù)據(jù)時,根據(jù)url生成的路徑查找當(dāng)前的臨時路徑下有無該文件庄吼,如果有說明該文件沒有下載完成缎除,則需要讀到這個文件然后做斷點續(xù)傳操作,讓該文件繼續(xù)下載总寻,而不是重頭開始下載器罐。
- (void)fileJudge{
//判斷當(dāng)前目錄下有無已有下載的臨時文件
if ([_fileManager fileExistsAtPath:self.videoTempPath]) {
//存在已下載數(shù)據(jù)的文件
_fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:self.videoTempPath];
_curruentLength = [_fileHandle seekToEndOfFile];
}else{
//不存在文件
_curruentLength = 0;
//創(chuàng)建文件
[_fileManager createFileAtPath:self.videoTempPath contents:nil attributes:nil];
_fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:self.videoTempPath];
}
//發(fā)起請求
[self sendHttpRequst];
}
//網(wǎng)路請求方法
- (void)sendHttpRequst
{
[_fileHandle seekToEndOfFile];
NSURL *url = [NSURL URLWithString:_videoUrl];
NSMutableURLRequest *requeset = [NSMutableURLRequest requestWithURL:url];
//指定頭信息 當(dāng)前已下載的進(jìn)度
[requeset setValue:[NSString stringWithFormat:@"bytes=%ld-", _curruentLength] forHTTPHeaderField:@"Range"];
//創(chuàng)建請求
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:requeset];
self.dataTask = dataTask;
//發(fā)起請求
[self.dataTask resume];
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (error == nil) { //下載成功
//當(dāng)前下載文件的臨時路徑
NSURL *tempPathURL = [NSURL fileURLWithPath:self.videoTempPath];
//緩存路徑
NSURL *cachefileURL = [NSURL fileURLWithPath:self.videoCachePath];
// 如果沒有該文件夾,創(chuàng)建文件夾
if (![self.fileManager fileExistsAtPath:self.videoCachePath]) {
[self.fileManager createDirectoryAtPath:self.videoCachePath withIntermediateDirectories:YES attributes:nil error:nil];
}
// 如果該路徑下文件已經(jīng)存在渐行,就要先將其移除轰坊,在移動文件
if ([self.fileManager fileExistsAtPath:[cachefileURL path] isDirectory:NULL]) {
[self.fileManager removeItemAtURL:cachefileURL error:NULL];
}
//移動文件至緩存目錄
[self.fileManager moveItemAtURL:tempPathURL toURL:cachefileURL error:NULL];
}
}