iOS开发 - 清理缓存

清理文件缓存

类型方法 (Type Methods) + 默认参数值(Default Parameter Values)
下面默认缓存目录为 /Library/Caches ,大家可以根据自己的缓存目录进行更改

iOS开发 - 清理缓存_第1张图片
XCache

使用:

    //读取缓存
    XCache.readCacheSize() //这里默认/Library/Caches目录
    XCache.readCacheSize("/Documents") //读取指定的目录

    //清除缓存
    XCache.cleanCache() //默认清除/Library/Caches目录
    XCache.cleanCache("/Documents") //清除指定的目录
    XCache.cleanCache("/Documents") { //带回调的清除
        print("清除的回调")
    }

XCache.swift

import UIKit

struct XCache {
    
    // MARK: - 读取缓存大小
    static func readCacheSize(filePath: String = "/Library/Caches") -> String {
        
        let cacheFilePath = NSHomeDirectory() + filePath
        let cacheSize = forderSizeAtPath(cacheFilePath)/1024/1024
        return String(format: "%.2f", cacheSize) + "MB"
    }

   //遍历所有目录及子目录
   static func forderSizeAtPath(folderPath: String) -> Double {
        let manage = NSFileManager.defaultManager()
        guard manage.fileExistsAtPath(folderPath) else { return 0 }
        let childFilePath = manage.subpathsAtPath(folderPath)!
        var fileSize:Double = 0
        for path in childFilePath {
            let fileAbsoluePath = folderPath + "/" + path
            fileSize += returnFileSzie(fileAbsoluePath)
        }
        return fileSize
    }
    
    //处理每个文件路径下文件 —> 大小
    static func returnFileSzie(path: String) -> Double {
        let manage = NSFileManager.defaultManager()
        var fileSize:Double = 0
        do {
            fileSize = try manage.attributesOfItemAtPath(path)["NSFileSize"] as! Double
        } catch {
            print(error)
        }
        return fileSize
    }
    
    
    //MARK: - 清除缓存
    static func cleanCache(filePath: String = "/Library/Caches", competion:() -> Void = { print("清除完毕") } ) {
        
        deleteFolder(NSHomeDirectory() + filePath)
        competion()
    }
    
    //删除文件夹的所有文件
    static func deleteFolder(folderPath: String) {
        let manage = NSFileManager.defaultManager()
        guard manage.fileExistsAtPath(folderPath) else { return }
        let childFilePath = manage.subpathsAtPath(folderPath)
        for path in childFilePath! {
            let fileAbsoluePath = folderPath + "/" + path
            deleteFile(fileAbsoluePath)
        }
    }
    
    //删除单个文件
    static func deleteFile(path: String) {
        let manage = NSFileManager.defaultManager()
        do {
            try manage.removeItemAtPath(path)
        } catch {
            print(error)
        }
    }
}

你可能感兴趣的:(iOS开发 - 清理缓存)