Delete all files and folder from a specific folder

I have a folder / Documents / Images, in this folder there are several other folders named for several years, in these folders I have images. I want to delete everything from the image folder (including folders and images in these folders).

I tried several code snippets but none of them delete folders

my method:

- (void) clearCache:(NSString *) folderName{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSFileManager *fm = [NSFileManager defaultManager]; NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:folderName]; NSLog(@"Removing items at path: %@",directory); NSError *error = nil; BOOL succes = [fm removeItemAtPath:directory error:&error]; /*for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) { //BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error]; BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file] error:&error]; if (!success || error) { // it failed. } }*/ 

}

+1
source share
2 answers

Your code ( [fm removeItemAtPath:directory error:&error]; ) should do this. If not, check the error it returns. If there are no errors, but you still see files / subfolders, the file reports an error!

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

+5
source
 NSFileManager *fm = [NSFileManager defaultManager]; NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"urDirectory/"]; NSError *error = nil; for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) { BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error]; if (!success || error) { // it failed. } } 

Hope this helps

+8
source

Source: https://habr.com/ru/post/913066/


All Articles