Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 670
NSExplorer Avatar asked Jan 20 '11 15:01

NSExplorer


2 Answers

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];
}
like image 79
cmlloyd Avatar answered Oct 25 '22 03:10

cmlloyd


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)
}
like image 34
footyapps27 Avatar answered Oct 25 '22 03:10

footyapps27