ios urlsession 不用afn 同时下载多个文件缓存到本地
需求是因为ffmpeg 在加载ts数据流的过程中
如果是频繁变换的网络流,比如3s一段的视频
对微软云的兼容性不好。因为ffmpeg的请求
是边下边播 对于不会变换url的网络请求来说
可以接受,但对于频繁变换的短时间url,又不是一次性
下载下来的,所以需要增加本地缓存策略
把所有的视频都下载到本地,然后再做播放策略。
1.写出urlsession 下载一个的接口然后写一个for循环让多个下载开启
2.这些请求都是异步的,根据对应关系就可以替换掉这些url了
3.判断urlsession 是不是同时发送消息出去的办法
就是使用wireshark抓包,发现请求发送都是同时
出去的。目前经过测试可以支持同时6个请求没有问题
4.如果要使用这个demo,注意没有进度条,因此这个只
适用于文件比较小的情况,还有一点是注意一下是否卡住了
主线程,其余都已经处理过了。
关键代码
//方法1
//特点:能够直接把文件下载到沙盒中,我们需要做文件剪切处理(不会有内存飙升的问题)
//缺点:无法监听文件的下载进度
//应用:小文件下载
+ (void)downloadFileDataWithBlock:(NSString *)urlString completionHandler:(void (^)(NSString *location, NSString *urlStr , NSError *error))completionHandler
{
// 设置配置
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPMaximumConnectionsPerHost = 10;
//1.确定URL
NSURL *url = [NSURL URLWithString:urlString];
//2.创建可变的请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setTimeoutInterval:15.0];
// 代理队列
NSOperationQueue *queue = [NSOperationQueue mainQueue];
//3.创建session
// NSURLSession *session = [NSURLSession sharedSession];
// 创建session
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:queue];
//4.创建task
/*
第一个参数:请求对象
第二个参数:completionHandler 当下载结束(成功|失败)的时候调用
location:位置,该文件保存到沙盒中的位置
response:响应头信息
error:错误信息
*/
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// NSLog(@"请求完成 url=[%@]",response.URL);
if (error == nil) {
NSLog(@"%@",location);
//6.处理文件
//6.1 获得文件的名称
NSString *fileName = response.suggestedFilename;
//6.2 写路径到磁盘+拼接文件的全路径
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileName];
//6.3 执行剪切操作
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
// NSLog(@"%@",fullPath);
completionHandler(fullPath,urlString,error);
} else {
NSLog(@"请求失败 url=[%@] error=[%@]",response.URL,error);
completionHandler(nil,response.URL,error);
}
}];
//5.执行task
[downloadTask resume];
}
看一下效果