CompC
CompC

Reputation: 415

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 {
        print(error.localizedDescription)
        if let reason = error.localizedFailureReason {
            print(reason)
        }
    }
}

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 contentsOfDirectoryAtPath method! How can it not exist? Does anybody know what's going on here, and how I can clear the cache?

Upvotes: 0

Views: 668

Answers (1)

rmaddy
rmaddy

Reputation: 318954

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.

Upvotes: 3

Related Questions