美文网首页
App获取缓存大小和清除缓存

App获取缓存大小和清除缓存

作者: 陈藩 | 来源:发表于2022-02-23 10:51 被阅读0次

    1.app获取缓存大小

    func getCacheFileSize() -> String{
        var foldSize:UInt64 = 0
        let filePath:String = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? ""
        if let files = FileManager.default.subpaths(atPath: filePath){
            for path in files{
                let temPath:String = filePath + "/" + path
                let folder = try? FileManager.default.attributesOfItem(atPath: temPath) as NSDictionary
                if let c = folder?.fileSize(){
                    foldSize += c
                }
            }
        }
        if foldSize > 1024 * 1024{
            return String.init(format: "%.2f", Double(foldSize)/1024.0/1024.0) + "MB"
        }
        else if foldSize > 1024{
            return String.init(format: "%.2f", Double(foldSize)/1024.0) + "KB"
        }else{
            return String(foldSize) + "B"
        }
    }
    

    2.清除缓存

     func clearFileCache(){
        let filePath:String = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? ""
        if let files = FileManager.default.subpaths(atPath: filePath){
            for path in files{
                let temPath:String = filePath + "/" + path
                if FileManager.default.fileExists(atPath: temPath){
                    try? FileManager.default.removeItem(atPath: temPath)
                }
            }
        }
    }

    相关文章

      网友评论

          本文标题:App获取缓存大小和清除缓存

          本文链接:https://www.haomeiwen.com/subject/yjlolrtx.html