Given a directory [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]
how do I delete ALL FILES in this folder?
(assume a correct documents directory path)
Given a directory [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]
how do I delete ALL FILES in this folder?
(assume a correct documents directory path)
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.
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
}
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)
}
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
}
}
Swift 4
do {
let destinationLocation:URL = ...
if FileManager.default.fileExists(atPath: destinationLocation.path) {
try! FileManager.default.removeItem(at: destinationLocation)
}
} catch {
print("Error \(error.localizedDescription)")
}