当我下载.mp4或.mov播放器时,它将毫无错误地保存到设备库中,但是当我尝试保存.m3u8视频文件时,它将始终在错误本地描述中显示此错误:
“可选(错误域= NSCocoaErrorDomain代码= -1 \”(空)\“)”
有人可以从我出问题的地方帮助我吗?
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
}
}
}
答案 0 :(得分:0)
下载视频时,会将视频保存到临时路径。 下载完成后,将视频从临时路径移动到您的应用目录。 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