Search code examples
objective-cios5nsfilemanager

Delete empty folders in iOS?


I have plenty of empty temporary folders in app's Document folder.

How to delete them all?

I tried:

NSArray *folders = [[NSFileManager defaultManager]contentsOfDirectoryAtURL:[self applicationDocumentsDirectory] includingPropertiesForKeys:[NSArray arrayWithObject:@"NSURLIsDirectoryKey"] options:0 error:nil];
if (folders) {
    for (NSURL *url in folders) {
        [[NSFileManager defaultManager]removeItemAtURL:url error:nil];
    }
}

but it deletes all, not only folders


Solution

  • This snippet of code deletes only directiories that are empty.

    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    for (NSString *file in files) {
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file];
        NSError *error;
        if ([[fileManager contentsOfDirectoryAtPath:fullPath error:&error] count]==0) {
            // check if number of files == 0 ==> empty directory
            if (!error) { 
                // check if error set (fullPath is not a directory and we should leave it alone)
                [fileManager removeItemAtPath:fullPath error:nil];
            }
        }
    }
    

    If you simply want to delete all directories (both empty and not empty) the snippet can be simplified into this:

    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    for (NSString *file in files) {
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file];
        if ([fileManager contentsOfDirectoryAtPath:fullPath error:nil])
            [fileManager removeItemAtPath:fullPath error:nil];
    }