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

Solution 1:

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:

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:

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:

- (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.