在视频的需求中,遇到这样一个需求,播放一视频的时候,要预下载
后面10条视频,但是只下载后面十条视频的前面1M
实现方法
1 创建请求时设置cacheLength
resource = [[IdiotResource alloc] init];
resource.requestURL = task.requestURL;
resource.requestOffset = task.requestOffset;
resource.fileLength = task.fileLength;
resource.cachePath = task.cachePath;
//预先下载1M
resource.cacheLength = 1024 * 1024;
resource.resourceType = IdiotResourceTypeNet;//网络资源
[self.resources addObject:resource];
二 创建请求时,设置 请求头的Range
- (void)fetchFromNetwork:(IdiotResource *)task withResource:(IdiotResource *)resource{
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[resource.requestURL originalSchemeURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
if (resource.cacheLength > 0) {
[request addValue:[NSString stringWithFormat:@"bytes=%lld-%lld", MAX(resource.requestOffset, task.requestOffset + task.cacheLength), resource.requestOffset+resource.cacheLength-1] forHTTPHeaderField:@"Range"];
}else{
[request addValue:[NSString stringWithFormat:@"bytes=%lld-", resource.requestOffset] forHTTPHeaderField:@"Range"];
}
NSURLSessionDataTask * datatask = [self.session dataTaskWithRequest:request];
datatask.taskDescription = [NSString stringWithFormat:@"%lld",task.requestOffset];
[datatask resume];
self.currentDataTask = datatask;
}
三 如何获取完整文件的大小
在 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
代理方法里面
通过获取响应头的 Content-Range 字段来获取,注意,不能通过
Content-Length来获取,因为这个时候Content-Length 是我们设置的请求部分的大小,不是完整的大小
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
IdiotResource * task = [self.taskDic objectForKey:dataTask.taskDescription];
if (task.cancel) return;
if (task.fileLength <= 0) {
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response;
NSString * contentRange = [[httpResponse allHeaderFields] objectForKey:@"Content-Range"];
NSString * fileLength = [[contentRange componentsSeparatedByString:@"/"] lastObject];
task.fileLength = fileLength.integerValue > 0 ? fileLength.integerValue : response.expectedContentLength;
}
if (self.currentResource.fileLength <= 0) {
self.currentResource.fileLength = task.fileLength;
}
if (!task.cachePath.length) {
task.cachePath = [IdiotFileManager createSliceWithUrl:task.requestURL sliceName:[NSString stringWithFormat:@"%lld-%lld",task.requestOffset,task.fileLength]];
}
if (self.currentResource.cacheLength <= 0) {
self.currentResource.cacheLength = task.fileLength - task.requestOffset;
}
completionHandler(NSURLSessionResponseAllow);
}
如下图,所示