Deleting all the files in the iPhone sandbox (documents folder)?

IphoneIosIos4

Iphone Problem Overview


Is there an easy way to delete all the files(images) I saved in the documents folder of the app?

Iphone Solutions


Solution 1 - Iphone

NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease];
NSError *error = nil;
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (error == nil) {
    for (NSString *path in directoryContents) {
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
        BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
        if (!removeSuccess) {
            // Error handling
            ...
        }
    }
} else {
    // Error handling
    ...
}

Solution 2 - Iphone

Code did not work with IOS 7 and Xcode 5 so edited to work with my app. Big credits to @Ole Begemann and @pablasso.

-(void)EmptySandbox
{
    NSFileManager *fileMgr = [[NSFileManager alloc] init];
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
    
    while (files.count > 0) {
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
        if (error == nil) {
            for (NSString *path in directoryContents) {
                NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
                BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
                files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
                if (!removeSuccess) {
                    // Error
                }
            }
        } else {
            // Error
        }
    }
}

Solution 3 - Iphone

For Swift devs:

let fileMgr = NSFileManager()
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
if let directoryContents = try? fileMgr.contentsOfDirectoryAtPath(dirPath)
{
    for path in directoryContents 
    {   
        let fullPath = (dirPath as NSString).stringByAppendingPathComponent(path)
        do 
	    {
		    try fileMgr.removeItem(atPath: fullPath)
		    print("Files deleted")
	    } 
	    catch let error as NSError 
	    {
		    print("Error deleting: \(error.localizedDescription)")
	    }
    }
}

Solution 4 - Iphone

- (void)removeFile
{
    // you need to write a function to get to that directory
    NSString *filePath = [self getDirectory];
    NSFileManager *fileManager = [NSFileManager defaultManager];  
    if ([fileManager fileExistsAtPath:filePath]) 
    {
        NSError *error;
        if (![fileManager removeItemAtPath:filePath error:&error])
        {
            NSLog(@"Error removing file: %@", error); 
        };
    }
}

I believe this is shorter.

Solution 5 - Iphone

Swift 2.1 with some extra's:

do {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    let documentsDirectoryURL = NSURL(fileURLWithPath: paths[0])
    
    let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(documentsDirectory)
    
    var totalMegaBytes: Double = 0
    var nrOfFiles = 0

    for filename in directoryContents {
        let file = documentsDirectoryURL.URLByAppendingPathComponent(filename)
        

        let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(file.path!)
        let fileSize = fileAttributes[NSFileSize] as! Double            
        totalMegaBytes += fileSize/1024/1024
        
        do {
            try NSFileManager.defaultManager().removeItemAtURL(file)
            nrOfFiles++
        }catch let error as NSError{
            print("> Emptying sandbox: could not delete file", filename, error)
        }
    }
    
    print("> Emptying sandbox: Removed \(nrOfFiles) files with a total of \(round(totalMegaBytes))MB")

}catch let error as NSError{
    print("> Emptying sandbox: Error emptying sandbox", error)
}

Solution 6 - Iphone

 NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease];
NSError *error = nil;
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
 if (error == nil) {
   for (NSString *path in directoryContents) {
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
    BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
    if (!removeSuccess) {
        // Error handling
        ...
    }
}
} else {
 // Error handling
...
}

Solution 7 - Iphone

It may not be applicable in all cases but generally it would be more efficient to put all the files in a custom directory inside Documents Directory and then use removeItemAtPath:error: to delete that directory and create it again. E.g.:

// Clear cache
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:cacheDirectory error:&error];
if (error)
{
    // error handling
}

// Create cache directory again
NSError *error2;
[[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:&error2];
if (error2)
{
    // error handling
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJinah AdamView Question on Stackoverflow
Solution 1 - IphoneOle BegemannView Answer on Stackoverflow
Solution 2 - IphoneMsmit1993View Answer on Stackoverflow
Solution 3 - IphoneTiberiu OpreaView Answer on Stackoverflow
Solution 4 - IphoneLuong Huy DucView Answer on Stackoverflow
Solution 5 - IphoneSamView Answer on Stackoverflow
Solution 6 - Iphonemahesh chowdaryView Answer on Stackoverflow
Solution 7 - IphoneAXEView Answer on Stackoverflow