Delete NSDocumentDirectory folder
I created a folder inside the documents directory using:
fileManager.createDirectory(atPath:ziPFolderPath,withIntermediateDirectories: false, attributes: nil)
I have placed several files in this folder.
Later in the application, I want to delete not only the files inside the specified folder, but also the folder. FileManager
supports the function removeItem
, but I'm wondering if it deletes the folder as well.
source to share
Yes, this will delete the folder as well.
From the documentation: - removeItem(at:)
Removes a file or directory at the specified URL.
From the documentation: - removeItem(atPath:)
Removes a file or directory at the specified path.
Edit: You can call it like this
try? FileManager.default.removeItem(at: URL(fileURLWithPath: ziPFolderPath))
//OR
try? FileManager.default.removeItem(atPath: ziPFolderPath)
source to share
-(BOOL)removeItemAtPath:(NSString *)path
error:(NSError * _Nullable *)error;
path is a string indicating the directory or folder to delete. Its NSFileManager.
you can also check here https://developer.apple.com/reference/foundation/nsfilemanager/1408573-removeitematpath?language=objc
source to share
Swift 5
Also you should check if the file exists in the path or not and also check for errors.
do {
let fileManager = FileManager.default
// Check if file exists
if fileManager.fileExists(atPath: urlfilePath) {
// Delete file
try fileManager.removeItem(atPath: urlfilePath)
} else {
print("File does not exist")
}
}
catch let error as NSError {
print("An error took place: \(error)")
}
}
source to share