iosswiftnsdocumentdirectory

Swift -Delete Custom Folder From Documents Directory


When recording videos I create a custom folder using "/MyFolder" like this:

guard let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return }
let dirPath = "\(documentsPath)/MyFolder/Videos_\(UUID().uuidString).mp4"

let outputFileURL = URL(fileURLWithPath: dirPath)
// ...

Now I have a function to delete just custom folders:

func deleteCustom(folder: String) {
    let fileManager = FileManager.default
    guard let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
    let customFolder = documentsDirectory.appendingPathComponent(folder)
    guard let filePaths = try? fileManager.contentsOfDirectory(at: customFolder, includingPropertiesForKeys: nil, options: []) else { return }
    for filePath in filePaths {
        try? fileManager.removeItem(at: filePath)
    }
}

In the function parameter should I pass in "MyFolder" or "/MyFolder"?


Solution

  • In the function parameter should I pass in "MyFolder" or "/MyFolder"?

    "MyFolder", because appendingPathComponent adds / automatically.