swift APP缓存

一、获取缓存

/// 获取缓存大小
    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) {
            
        }
    }

你可能感兴趣的:(swift学习,swift,缓存)