How to delete the contents of the Documents directory (and not the Documents directory itself)?
-
13-10-2019 - |
Question
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?
Solution
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];
}
OTHER TIPS
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)
}
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)
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow