How to delete ALL FILES in the specified application directory?

Given the directory [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"] , how to delete ALL FILES in this folder?

(Assume the correct document catalog path)

+44
filesystems objective-c iphone cocoa-touch
Feb 09 '10 at 3:40
source share
3 answers
 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 this for you to do something useful with a mistake, if it exists.

+110
Feb 09 '10 at 3:50
source share
β€” -

if you want to delete files and the directory itself, 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 } 
+16
Apr 11 2018-12-11T00:
source share

for fast lovers:

  let fm = NSFileManager.defaultManager() do { let folderPath = ... let paths = try fm.contentsOfDirectoryAtPath(folderPath) for path in paths { try fm.removeItemAtPath("\(folderPath)/\(path)") } } catch let error as NSError { print(error.localizedDescription) } 
+11
Jan 18 '16 at 9:32
source share



All Articles