1

I have a /Documents/Images folder , in that folder are several other folders named after years , in those folders i have images. I want to delete everything from the images folder ( including the folders and the images in these folders).

I tried several code snippets but none delete the 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.
    }
}*/

}

SnK
  • 528
  • 1
  • 11
  • 32
  • possible duplicate of [How to delete ALL FILES in a specified directory on the app?](http://stackoverflow.com/questions/2226600/how-to-delete-all-files-in-a-specified-directory-on-the-app) – Leena Aug 31 '14 at 10:53

2 Answers2

8
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

visakh7
  • 26,380
  • 8
  • 55
  • 69
5

Your code ([fm removeItemAtPath:directory error:&error];) should do it. If it doesn't, inspect the error it returns. If there's no error, but you still see files/subfolders - file a bug report!

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

Steven Kramer
  • 8,473
  • 2
  • 37
  • 43