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?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With