How to delete the contents of the Documents directory (and not the Documents directory itself)?

10,305

Solution 1

Try this:

NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
    [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
}

Solution 2

Swift 3.x

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
guard let items = try? FileManager.default.contentsOfDirectory(atPath: path) else { return }

for item in items {
    // This can be made better by using pathComponent
    let completePath = path.appending("/").appending(item)
    try? FileManager.default.removeItem(atPath: completePath)
}

Solution 3

I think that working with URLs instead of String makes it simpler:

private func clearDocumentsDirectory() {
    let fileManager = FileManager.default
    guard let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

    let items = try? fileManager.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil)
    items?.forEach { item in
        try? fileManager.removeItem(at: item)
    }
}
Share:
10,305

Related videos on Youtube

NSExplorer
Author by

NSExplorer

Updated on February 25, 2021

Comments

  • NSExplorer
    NSExplorer over 2 years

    I want to delete all the files and directories contained in the Documents directory.

    I believe using [fileManager removeItemAtPath:documentsDirectoryPath error:nil] method would remove the documents directory as well.

    Is there any method that lets you delete the contents of a directory only and leaving the empty directory there?

  • said altintop
    said altintop over 2 years
    Thanks for the codes. The codes also work with Swift 5.

Related