Delete specific extension files from sandbox

This content has 12 years. Please, read this page keeping its age in your mind.

Let’s say that me app creates temporarily pdf and png files on Documents folder of the app.

It’s good manners to delete the files when your app terminates or go to the background (it depends).

Let’s see a chunk of code that do the job

- (void)removeTempFilesFromDocuments
{
    NSError *error;
    
    // get the documents folder of your sandbox
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSArray *dirFiles;
    if ((dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error]) == nil) {
        // handle the error
    };
    
    // find the files with the extensions you want
    NSArray *pdfFiles = [dirFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.pdf'"]];
    NSArray *pngFiles = [dirFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"]];
    
    
    // loop on arrays and delete every file corresponds to specific filename
    for (NSString *fileName in pdfFiles) {
        if (![[NSFileManager defaultManager] removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:fileName] error:&error]) {
            // handle the error
        }
    }
    for (NSString *fileName in pngFiles) {
        if (![[NSFileManager defaultManager] removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:fileName] error:&error]) {
            // handle the error
        }
    }
}

Enjoy!

One thought on “Delete specific extension files from sandbox

Comments are closed.