CompC CompC - 1 year ago 71
Swift Question

NSFileManager: Trying to delete files, but it says they don't exist

I'm trying to delete the files in my cache directory. However, when I tried to delete individual folders, I got an error saying the file doesn't exist, even though I know it does. So, I tried using a for loop to delete the all the files in the caches directory.

do {
for file in try NSFileManager.defaultManager().contentsOfDirectoryAtPath(cacheFolderPath) where !file.hasPrefix("."){
try NSFileManager.defaultManager().removeItemAtPath(file)
print("Cache cleared successfully.")
catch let error as NSError {
if let reason = error.localizedFailureReason {

However, this code prints this:

"CategoryThumbnails" couldn't be removed.

The file doesn't exist.

Well, it obviously does exist, as it was discovered by the
method! How can it not exist? Does anybody know what's going on here, and how I can clear the cache?

Answer Source

The results of contentsOfDirectoryAtPath is a list of files in the given folder. But each of those results is not a complete path itself.

To delete each file, you need to append file to cacheFolderPath. Then pass that complete path to removeItemAtPath.

Another solution is to use one of the other folder enumeration methods of NSFileManager that return full URLs and let your provide options to skip hidden files.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download