let urlString: String = videoModel?.videoUrl ?? ""
let session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
downloadTask = session.downloadTask(with: urlString.url!)
downloadTask?.resume()
extension ShowVideoVC: URLSessionDelegate, URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
//1.拿到cache文件夹的路径
let cache = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last
//2,拿到cache文件夹和文件名
let file: String = cache?.appendingPathComponent(downloadTask.response?.suggestedFilename ?? "") ?? ""
do {
try FileManager.default.moveItem(at: location, to: URL.init(fileURLWithPath: file))
} catch let error {
print(error)
}
//3,保存视频到相册
let videoCompatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file)
//判断是否可以保存
if videoCompatible {
UISaveVideoAtPathToSavedPhotosAlbum(file, self, #selector(didFinishSavingVideo(videoPath:error:contextInfo:)), nil)
} else {
JJHUDManage.show("该视频无法保存至相册")
}
}
@objc func didFinishSavingVideo(videoPath: String, error: NSError?, contextInfo: UnsafeMutableRawPointer?) {
if error != nil{
JJHUDManage.errorShow("保存失败")
JJLog(error?.localizedDescription)
}else{
JJHUDManage.successShow("保存成功")
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
// //下载进度
// CGFloat progress = totalBytesWritten / (double)totalBytesExpectedToWrite;
// dispatch_async(dispatch_get_main_queue(), ^{
// //进行UI操作 设置进度条
// self.progressView.progressValue = progress;
// self.progressView.contentLabel.text = [NSString stringWithFormat:@"%.2f%%",progress*100];
// });
}
}
iOS开发笔记-102:Swift5 - 通过url下载视频,保存视频
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- NSString *urlString = @"http://1234567890/xxx"; NSData *d...