STerrier
STerrier

Reputation: 4015

Swift - Video file array save to app gallery fine but not properly to the app document directory

I am trying to save an array of videos using a for loop to the document directory and gallery but the document directory is only saving the last video whereas the gallery has all of them saved without issues.

Any ideas how can this be fixed? Thanks for the input!

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")
                    }
                }
           }
        }

    }
}

For Loop

videoList = videoArray()

    for videos in videoList {

        saveVideoToGallery(videoUrl: videos)
    }

Upvotes: 0

Views: 295

Answers (1)

inokey
inokey

Reputation: 6170

It looks like the problem in these lines.

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

You're basically overwriting your video with the same fileName because every time it takes some global scope variable self.videoURL which I don't see chaining anywhere. Try to generate a unique file name for different videos for example using UUID string

let fileName = UUID().uuidString

Upvotes: 1

Related Questions