首页 > 解决方案 > Swift - 视频文件数组可以很好地保存到应用程序库,但不能正确保存到应用程序文档目录

问题描述

我正在尝试使用 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)
    }

标签: arraysswiftvideodirectorysave

解决方案


看起来这些行中的问题。

let fileName = String(self.videoURL)
let filePath = "\(documentsPath + "/ImportVideo")" + fileName

你基本上用相同的方式覆盖你的视频,fileName因为每次它需要一些全局范围变量self.videoURL,我看不到在任何地方链接。尝试为不同的视频生成一个唯一的文件名,例如使用UUID字符串

let fileName = UUID().uuidString


推荐阅读