当我下载 .mp4 或 .mov 播放器时,它会保存到设备库中,没有任何错误,但当我尝试保存 .m3u8 视频文件时,它总是会在错误本地描述中给出此错误:
“可选(错误域=NSCocoaErrorDomain代码=-1\“(null)\”)”
任何人都可以帮我解决我出错的地方吗?
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
// 1
guard let sourceURL = downloadTask.originalRequest?.url else { return }
let download = DownloadManager.sharedDownloadManager.activeDownloads[sourceURL]
DownloadManager.sharedDownloadManager.activeDownloads[sourceURL] = nil
// 2
let destinationURL = localFilePath(for: sourceURL)
print(destinationURL)
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)
}) { saved, error in
if saved {
print("Video saved")
download?.track.downloaded = true
}else{
print("Video not saved")
download?.track.downloaded = false
}
}
}
最佳答案
当您下载视频时,您会将视频保存到临时路径。 下载完成后,将视频从临时路径移动到您的应用程序目录。 check Here
它使用此代码下载视频,这对我来说非常适合
您只需在函数中传递视频链接即可。 我使用日期格式化程序来命名从服务器下载的视频。 因为下载第一个视频后,如果您不使用任何命名约定,您的旧视频将被替换。
func downloadVideoLinkAndCreateAsset(_ videoLink: String) {
DispatchQueue.main.async {
self.view.makeToast("Downloading Video", duration: 0.8, position: .center)
}
guard let videoURL = URL(string: videoLink) else { return }
guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
URLSession.shared.downloadTask(with: videoURL) { (location, response, error) -> Void in
guard let location = location else { return }
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "GMT")
let destinationURL = documentsDirectoryURL.appendingPathComponent("\(dateFormatter.string(from: date)).mp4")
do {
try FileManager.default.moveItem(at: location, to: destinationURL)
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)}) { completed, error in
if completed {
//Downloaded
} else if let error = error {
//Error
}
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
目标 URL 是您的项目目录的 URL
关于ios - 将流媒体视频(m3u8 文件)保存到图库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53928211/