Search code examples
swiftnsfilemanagernsdocumentdirectory

How to check if multiple files exist in documents directory? (Swift)


I can check if one file exists with this method:

let fileNameOne = "savedpicture1"
let fileURLOne = documentsDirectoryURL.appendingPathComponent(fileNameOne) 

if !FileManager.default.fileExists(atPath: fileURLOne.path) {
       removeImage(itemName: "savedpicture1", fileExtension: "jpg")
 } else {
        print("There was no image to remove")
 }

My problem is having to repeat the same lines of code for multiple files. For instance, I would like to check if the files exist in an array of paths, but I would have to repeat the code from above for each file, and it seems too redundant. I'm wondering if there's a way to check multiple files instead of repeating the code for each single path. ".fileExists" only enables me to check one path:

 let filePaths = [fileURLOne.path, fileURLTwo.path, fileURLThree.path, 
 fileURLFour.path] 

Solution

  • Write a method for example

    func checkFiles(with fileNames: [String] {
        for fileName in fileNames {
            let fileURL = documentsDirectoryURL.appendingPathComponent(fileName) 
            if !FileManager.default.fileExists(atPath: fileURL.path) {
                removeImage(itemName: fileName, fileExtension: "jpg")
            } else {
                print("There was no image to remove at", fileURL)
            }
        }
    }
    

    and call it

    let fileNames = ["savedpicture1", "savedpicture2", "savedpicture3",  "savedpicture4"] 
    checkFiles(with: fileNames)