How to delete ALL FILES in a specified directory on the app?
Given a directory [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]
how do I delete ALL FILES in this folder?
(assume a correct documents directory path)
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
}