我正在尝试使用for循环将一系列视频保存到文档目录和图库,但是文档目录仅保存了最后一个视频,而图库已保存了所有视频而没有问题。
任何想法如何解决?感谢您的输入!
func saveVideoToGallery(videoUrl: String) {
//currently a URL placeholder
let videoMainUrl =
"https://dev.server.com/storage/sessions/0001/imports/"
let videoUrlPicked = String(videoMainUrl + videoUrl)
let mainPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
let folderPath = mainPath + "/ImportVideo"
var objCBool:ObjCBool = true
// Create Directory Folder if doesn't exists
let isExist = FileManager.default.fileExists(atPath: folderPath, isDirectory: &objCBool)
if !isExist {
do {
try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
} catch {
print("error")
}
}
DispatchQueue.global(qos: .background).async {
if let url = URL(string: videoUrlPicked),
let urlData = NSData(contentsOf: url) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
let fileName = String(self.videoURL)
let filePath = "\(documentsPath + "/ImportVideo")" + fileName
//Save the video file to directory folder "ImportVideo"
urlData.write(toFile: filePath, atomically: true)
DispatchQueue.main.async {
//Save to the gallery
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
}) { completed, error in
if completed {
print("Video is saved to gallery")
}
}
}
}
}
}
用于循环
videoList = videoArray()
for videos in videoList {
saveVideoToGallery(videoUrl: videos)
}
答案 0 :(得分:1)
在这些行中看起来像是问题。
let fileName = String(self.videoURL)
let filePath = "\(documentsPath + "/ImportVideo")" + fileName
基本上,您使用相同的fileName
覆盖了视频,因为每次都需要一些全局范围变量self.videoURL
时,我看不到任何链接。尝试使用UUID
字符串为不同的视频生成唯一的文件名
let fileName = UUID().uuidString