How to delete the contents of the Documents directory (and not the Documents directory itself)?
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];
}
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)
}
}