How to delete files from fron iOS temp directory?

I used the code to delete temp directory files while using the device.

-(void) clearAllTempFiles {
    NSString *path = NSTemporaryDirectory();
    if ([path length] > 0)
    {
        NSError *error = nil;  
        NSFileManager *fileManager = [NSFileManager defaultManager];

        BOOL deleted = [fileManager removeItemAtPath:path error:&error];

        if (deleted != YES || error != nil)
        {

        }
        else{
            // Recreate the Documents directory
            [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
        }

    }
}

      

is it not working fine? is this the correct code to delete files from temp directory?

Help me?

+3


source to share


2 answers


You can get the name of the tmp directory on your mac using this in your code:

code:

(void)cacheDirectory {

    NSString *tempPath = NSTemporaryDirectory();

    NSLog(@"Temp Value = %@", items);
}

      

Call the method from anywhere.

This will return the name of the tmp folder, then in finder do (cmd-shift-G) and paste the answer you got from the console window.



The following will clear the TMP directory used by the simulator.

code:

NSString *tempPath = NSTemporaryDirectory();
NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:tempPath];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"]];

NSFileManager *fileManager = [NSFileManager defaultManager];

if (onlyJPGs) { 
    for (int i = 0; i < [onlyJPGs count]; i++) {
    NSLog(@"Directory Count: %i", [onlyJPGs count]);
    NSString *contentsOnly = [NSString stringWithFormat:@"%@%@", tempPath, [onlyJPGs objectAtIndex:i]];
    [fileManager removeItemAtPath:contentsOnly error:nil];
}

      

The above code only clears the JPG from the directory, so if you want to remove anything else change it.

+6


source


I found simple



NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
for (NSString *file in tmpDirectory) {
    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
}

      

+4


source







All Articles