51

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

Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
Jinah Adam
  • 1,125
  • 2
  • 14
  • 27
  • http://stackoverflow.com/questions/4792663/remote-wipe-of-application-data-in-ios this is a similar question assuming he wants to delete everything in the documents folder, but no solution yet – Jinah Adam Jan 25 '11 at 12:12

7 Answers7

95
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
    ...
}
pablasso
  • 2,479
  • 2
  • 26
  • 32
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • 1
    it worked for the most part. but it turns out it removeItemAtPath requires full file path. so i used this NSString *myFilePath = [documentsDir stringByAppendingPathComponent:path]; thanks. – Jinah Adam Jan 25 '11 at 12:43
  • 1
    That's right, Jinah. My error. I am gonna correct the code above. – Ole Begemann Jan 25 '11 at 12:45
  • 2
    If this works, it would be nice to remove the `Untested code:` comment. Thanks – Warpspace Feb 09 '12 at 08:58
  • I get an EXC_BAD_ACCESS every time I execute this. But it deletes the contents of my sand box though. How do I prevent the error? Any ideas? – acecapades Aug 10 '12 at 07:50
  • 1
    I got documentsDirectory as undeclared Identifier. using NSDocumentDirectory also does not work in its place. It says, incompatible integer to pointer conversion. – Ankit Tanna Aug 21 '13 at 08:07
  • What is documentsDirectory? – Dog Sep 09 '15 at 15:41
  • @Wonder Dog - Well, just write NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; – Dog Sep 09 '15 at 15:43
15

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
        }
    }
}
Msmit1993
  • 1,710
  • 4
  • 21
  • 35
  • If you're using CoreData, just note this will delete your Model also – BenB Mar 20 '14 at 23:35
  • Thank you, this code works like a charm. I'm a newbie and i happen to overwrite the stored archive NSMutableArray with NSMutableDictionary on the iPad. Save my life – chrizonline Oct 22 '14 at 04:23
15

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)")
        }
    }
}
Tiberiu Oprea
  • 191
  • 1
  • 6
7
- (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.

Luong Huy Duc
  • 458
  • 7
  • 17
5

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)
}
Sam
  • 5,375
  • 2
  • 45
  • 54
  • I get "error thrown from here are not handled because the enclosing catch is not exhaustive" – Luda Dec 08 '15 at 16:18
  • I am upvoting you. But you should really consider removing this: "let error as NSError". Or maybe have some other solution for the above error – Luda Dec 08 '15 at 16:23
  • 1
    I don't get that warning. Isn't NSError as exhaustive as possible? – Sam Dec 10 '15 at 15:35
2
 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
...
}
mahesh chowdary
  • 432
  • 5
  • 13
2

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
}
AXE
  • 8,335
  • 6
  • 25
  • 32