【问题标题】:How can I purge just images in cache directory?如何仅清除缓存目录中的图像?
【发布时间】:2017-07-29 02:41:21
【问题描述】:

我想每 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)")
    }

【问题讨论】:

    标签: ios swift image caching


    【解决方案1】:

    可能性:

    您可以在删除之前使用 ImageIO 测试每个文件,但这意味着在删除之前阅读它。它将取代对后缀 BUT 的测试

    因为这真的太贵了恕我直言,我什至不会提供代码。

    好吧:

    => 重命名您的图像,使其具有后缀或前缀,以便您可以通过名称识别它们(n 次调用)

    好办法

    => 将图像放在单独的文件夹中,然后删除文件夹以清除它们。 (1 次通话)

    【讨论】:

    • 如何重命名默认缓存系统缓存的图片?
    • 如果我把它们放在一个单独的文件夹中,如果出现内存警告,iOS 可以删除它们吗?还是我应该手动处理?
    • 除了 ios 默认缓存文件夹中的图像之外,什么是缓存?还有什么吗?
    猜你喜欢
    • 2011-02-22
    • 2011-04-12
    • 2011-02-25
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2012-11-12
    • 2013-06-23
    • 1970-01-01
    相关资源
    最近更新 更多