功能介绍:需要将转码后的视频(小于20MB),通过APP下载至手机相册,可以将小视频分享至微信传播。
1.通过服务器转码视频,或者很多云服务商都会提供这个功能。
2.通过APP下载至手机相册,这个是咱们需要做的事。
主要技术:用到 URLSession 和 URLSessionDownloadDelegate
1.创建 session 下载任务 并执行(由于下载的视频比较小,所有就不用分段下载了)
// 初始化 session let config = URLSessionConfiguration.default; let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue()); // 视频地址 let url = URL(string: urlStr.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)!); // 创建请求 let request = URLRequest(url: url!); let download = session.downloadTask(with: request); // 开始任务,session 任务默认都是挂起的,需要 resume 才能执行 download.resume();
2.设置 URLSessionDownloadDelegate 代理方法
//下载完成时调用,location 是下载完成后的路径 @available(iOS 7.0, *) public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) //下载进度,下载过程中会多次调用 //bytesWritten: 本次写入的字节数,totalBytesWritten:已经写入的字节数(目前下载的字节数),totalBytesExpectedToWrite:总得下载字节数(文件的总大小) @available(iOS 7.0, *) optional public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) //继续下载, @available(iOS 7.0, *) optional public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64)上代码
// 完成调用 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { // 1.输出 location 是 "file:///user..." 格式,需要将 file:// 截掉,并转换成 String 格式 // 2.下载完成后的文件默认保存在沙盒tmp文件夹(临时文件)中,该方法结束后系统会自动删除,所以需要转存并且修改文件格式 // 将源文件 URL 地址转成 String let locationStepOne = location.absoluteString as NSString; // 截掉 file:// let locationStepTwo = locationStepOne.substring(from: 7); // 创建文件管理器 let manager = FileManager.default; // 目标地址 cache 文件夹下 let pathArray = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true); // 生成目标地址 let copyPath = pathArray.first! + "/video.mov"; // 判断文件是否存在,存在就删除 let exist = manager.fileExists(atPath: copyPath); if exist { // 有,则删除 let cancel:Bool = ((try?manager.removeItem(atPath: copyPath)) != nil); if !cancel { return; } } // 复制文件 tmp -> cache let save:Bool = ((try? manager.moveItem(atPath: locationStepTwo, toPath: copyPath)) != nil); if save { // 检测文件是否可以保存至相册 if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(copyPath) { // 存入相册 UISaveVideoAtPathToSavedPhotosAlbum(copyPath, self, nil, nil); } } else { print("失败"); } } // 下载进度 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { // 获取进度 let written:Float = (Float)(totalBytesWritten); let total:Float = (Float)(totalBytesExpectedToWrite); let progress:Float = written/total; } // 继续下载 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { }