我想每1分钟清除默认缓存目录中的所有图像,但是缓存文件没有扩展名来指定它们的类型,我不知道如何删除像PNG这样的图像(而不是其他数据)。这是我在这个网站上看到的示例代码:
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)")
}发布于 2017-03-08 21:46:12
可能性:
您可以在删除每个文件之前使用ImageIO对其进行测试,但这意味着在删除它之前要先阅读它。它会取代后缀的测试,但是
因为这真的是不必要的昂贵,我甚至不会提供代码。
好的方式:
=>将您的图像重命名为后缀或前缀,以便您可以通过名称来识别它们(n个调用)
好方法
=>将图像放在一个单独的文件夹中,然后删除该文件夹以清除它们。(1个电话)
https://stackoverflow.com/questions/42672877
复制相似问题