How to delete ALL FILES in a specified directory on the app?

40,498

Solution 1

NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
    BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
    if (!success || error) {
        // it failed.
    }
}

I leave it up to you to do something useful with the error if it exists.

Solution 2

if you want to remove files and the directory itself then use it without for loop

NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos"];
NSError *error = nil;
BOOL success = [fm removeItemAtPath:cacheImageDirectory error:&error];
if (!success || error) {
    // something went wrong
}

Solution 3

same for swift lovers:

let fm = FileManager.default
do {
  let folderPath = "...my/folder/path"
  let paths = try fm.contentsOfDirectory(atPath: folderPath)
  for path in paths
  {
    try fm.removeItem(atPath: "\(folderPath)/\(path)")
  }
} catch {
  print(error.localizedDescription)
}

Solution 4

Most of the older answers have you use contentsOfDirectoryAtPath:error: which will work, but according to Apple:

"The preferred way to specify the location of a file or directory is to use the NSURL class"

so if you want to use NSURL instead you can use the method contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: so it would look something like this:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray<NSURL*> *urls = [fileManager contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];

    for (NSURL *url in urls)
    {
        NSError *error = nil;
        BOOL success = [fileManager removeItemAtURL:url error:error];
        if (!success || error) {
            // something went wrong
        }
    }
Share:
40,498

Related videos on Youtube

RexOnRoids
Author by

RexOnRoids

Just some kid.

Updated on February 04, 2020

Comments

  • RexOnRoids
    RexOnRoids about 4 years

    Given a directory [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"] how do I delete ALL FILES in this folder?

    (assume a correct documents directory path)

  • zekel
    zekel over 12 years
    In general, you should probably use stringByAppendingPathComponent instead of stringWithFormat to concatenate paths. (I know the above works, but only because of your hard-coded trailing slash in @"Photos/".)
  • karlbecker_com
    karlbecker_com almost 11 years
    Zekel is correct - it's important to use stringByAppendingPathComponent, especially if you are, say, using it with iOS.
  • Danny
    Danny over 7 years
    Actually the above code as it stands does not work because stringByAppendingPathComponent strips the hardcoded slash from @"Photos/" so that when you try to use directory variable later, it does not include the slash that should separate it from file. A quick fix is to remove the hardcoded trailing slash when creating the directory variable and adding the slash into the stringWithFormat call between %@%@
  • strikerdude10
    strikerdude10 over 7 years
    You probably want to move [fm contentsOfDirectoryAtPath:directory error:&error] out of the for loop so it doesn't call that method on each iteration. Something like NSArray<NSString*> *contents = [fm contentsOfDirectoryAtPath:documentsPath error:&error]; and for (NSString *file in contents)
  • iOS Geek
    iOS Geek over 6 years
    Worked for me Thanks just needed a little modification, Thanks
  • Andrew Vergunov
    Andrew Vergunov over 6 years
    It shouldn't be force after try, if you are using catch. Also, you're trying to remove file by URL, not all files by path.
  • strikerdude10
    strikerdude10 about 6 years
    From Apple: "Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended", meaning you shouldn't check if the file exists before removing it. You should just try and delete the file and then handle the error appropriately. Check out the documentation on fileExists(atPath:) for more info.