swift APP缓存

这里的APP缓存是指Cache文件夹里的内容,iOS系统从iOS 10开始就支持系统自动清理功能了。

建议重要的内容不要放到 Cache文件夹中。

一、获取缓存

复制代码
/// 获取缓存大小
    public static func getCacheSize() -> String {
        let folderPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? ""
        let manager = FileManager.default
        guard let files = manager.subpaths(atPath: folderPath)
        else {
            return "0.0B"
        }
        var folderSize = 0.0
        for path in files {
            let temPath: String = folderPath + "/" + path
            let folder = try? manager.attributesOfItem(atPath: temPath) as NSDictionary
            if let c = folder?.fileSize() {
                folderSize += Double(Float(c))
            }
        }
        // 保留2位小数
        if folderSize > 1024 * 1024 {
            return String(format: "%.2f", Double(folderSize)/1024.0/1024.0) + "MB"
        } else if folderSize > 1024 {
            return String(format: "%.2f", Double(folderSize)/1024.0) + "KB"
        } else {
            return String(folderSize) + "B"
        }
    }

二、清除缓存

复制代码
/// 清理缓存
    public static func cleanCache(_ block: (() -> Void)?) {
        DispatchQueue.global().async {
            // 文件路径
            let folderPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? ""
            if let files = FileManager.default.subpaths(atPath: folderPath) {
                for path in files {
                    let temPath: String = folderPath + "/" + path
                    if FileManager.default.fileExists(atPath: temPath) == true {
                        try? FileManager.default.removeItem(atPath: temPath)
                    }
                }
            }
            // 返回主线程
            DispatchQueue.main.async {
                if let block = block {
                    block()
                }
            }
        }
    }

三、清除网页缓存

复制代码
/// 清除网页缓存
    public static func cleanWebCache() {
        let types = [WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeDiskCache]
        let websiteDataTypes = Set(types)
        let dateFrom = Date(timeIntervalSince1970: 0)
        WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: dateFrom) {
            
        }
    }
相关推荐
墨者阳1 天前
数据库的自我修炼
数据库·sql·缓存·性能优化
猫豆~1 天前
Ansible自动运维——6day
linux·数据库·sql·缓存·云计算
今晚务必早点睡2 天前
Redis——快速入门第一课:了解redis
数据库·redis·缓存
今晚务必早点睡2 天前
Redis——快速入门第三课:真实项目里的缓存完整流程
数据库·redis·缓存
-Xie-2 天前
Redis(十五)——内存过期/淘汰策略
数据库·redis·缓存
小股虫2 天前
Tair Java实操手册:从零开始的缓存中间件入门指南
java·缓存·中间件
Hello.Reader2 天前
KeyDB 一台“40 英尺卡车”式的 Redis 兼容高性能缓存
数据库·redis·缓存
最贪吃的虎2 天前
网络是怎么传输的:从底层协议到浏览器访问网站的全过程剖析
java·开发语言·网络·http·缓存
一心0922 天前
zabbix proxy 参数优化-配置缓存使用率(%)> 85%
缓存·zabbix·zabbix proxy
kyle~2 天前
计算机系统---缓存不命中(Cache Miss)
缓存