I downloaded some PDF files in my app and want to delete these on closing the application.
For some reason it does not work:
Creating the file:
l
This code works for me. I removed all the images that were cached.
private func test(){
let fileManager = NSFileManager.defaultManager()
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL
let documentsPath = documentsUrl.path
do {
if let documentPath = documentsPath
{
let fileNames = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
print("all files in cache: \(fileNames)")
for fileName in fileNames {
if (fileName.hasSuffix(".png"))
{
let filePathName = "\(documentPath)/\(fileName)"
try fileManager.removeItemAtPath(filePathName)
}
}
let files = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
print("all files in cache after deleting images: \(files)")
}
} catch {
print("Could not clear temp folder: \(error)")
}
}
**** Update swift 3 ****
let fileManager = FileManager.default
let documentsUrl = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL
let documentsPath = documentsUrl.path
do {
if let documentPath = documentsPath
{
let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
print("all files in cache: \(fileNames)")
for fileName in fileNames {
if (fileName.hasSuffix(".png"))
{
let filePathName = "\(documentPath)/\(fileName)"
try fileManager.removeItem(atPath: filePathName)
}
}
let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
print("all files in cache after deleting images: \(files)")
}
} catch {
print("Could not clear temp folder: \(error)")
}
I believe your problem is on this line:
let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")
You're using contentsOfDirectoryAtPath()
with something that is an NSURL
. You choose either path strings or URLs, not try to mix them both. To pre-empty your possible next question, URLs are preferred. Try using contentsOfDirectoryAtURL()
and removeItemAtURL()
.
Another curious thing you should look at once you resolve the above: why are you using NSTemporaryDirectory()
for the file path when you try to delete? You're reading the document directory and should use that.