美文网首页
Swift 文件缓存处理

Swift 文件缓存处理

作者: 取名困难综合症患者 | 来源:发表于2016-06-08 16:22 被阅读652次

    创建CacheManager 管理文件缓存

    1.0 提供readCacheSize()和cleanCache()方法分别为读取和清除文件缓存

    readCacheSize()读取缓存

    static func readCacheSize()->String {
            return String(format: "%.2f",forderSizeByDocumentPath(NSHomeDirectory()))
        }
    

    2.1 forderSizeByDocumentPath()遍历所有子目录 并计算文件大小

     static func forderSizeByDocumentPath(forderPath: String) -> Double {
            let manage = NSFileManager.defaultManager()
            if !manage.fileExistsAtPath(forderPath) {
                print("文件不存在")
            }
            let subFilePath = manage.subpathsAtPath(forderPath)!
            var fileSize:Double = 0
            for path in subFilePath {
                let fileAbsoluePath = forderPath + "/" + path
                fileSize += retureFileSize(fileAbsoluePath)
            }
            return fileSize
        }
    

    2.2 retureFileSize()计算单个文件大小

    static func retureFileSize(path:String)-> Double{
            let manage = NSFileManager.defaultManager()
            var fileSize: Double = 0.0
            do{
                fileSize = try manage.attributesOfItemAtPath(path)["NSFileSize"] as! Double
            }catch{
                print("未知错误")
            }
            return fileSize/1024/1024
        }
    

    cleanCache()清除缓存

    static func cleanCache(competion:()->Void){
            CacheManager.deleteFolder(NSHomeDirectory()+"/Documents")
            CacheManager.deleteFolder(NSHomeDirectory()+"/Library")
            CacheManager.deleteFolder(NSHomeDirectory()+"/tmp")
            competion()
        }
    

    3.1 deleteFolder()删除文件夹下的所有文件

    static func deleteFolder(folderPath:String){
            let manage = NSFileManager.defaultManager()
            if !manage.fileExistsAtPath(folderPath) {
            }
            let childFilePath = manage.subpathsAtPath(folderPath)
            for path in childFilePath!{
                let fileAbsoluePath = folderPath+"/"+path
                CacheManager.deleteFile(fileAbsoluePath)
            }
        }
    

    3.2 deleteFile()删除单个文件

    static func deleteFile(path:String){
            let manage = NSFileManager.defaultManager()
            do{
                try manage.removeItemAtPath(path)
            }catch{
                
            }
        }
    

    结语

    项目链接:文件缓存

    相关文章

      网友评论

          本文标题:Swift 文件缓存处理

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