swift计算目录缓存和清除操作

import UIKit

class XCache: NSObject {

    /**
     读取缓存大小 单位:MB
     */
    public static func calculateCacheSize(filePath: String) -> String {
        return String(format: "%.2f", XCache.forderSizeAtPath(folderPath: filePath))
    }
    /**
     清除缓存
     */
    public static func cleanCache(filePath:String, completion:()->Void){
        XCache.deleteFolder(folderPath: filePath)
        completion() // 完成后的回调
    }
    
    /**
    计算单个文件的大小 单位:MB
     path: 文件的路径
     返回单个文件的大小
    */
    private static func returnSingleFileSize(path: String) -> Double {
        
        var fileSize: Double = 0
        do {
            let fileAttributes = try FileManager.default.attributesOfItem(atPath: path)
            let fileSizeNumber = fileAttributes[FileAttributeKey.size] as! NSNumber
            fileSize = Double(fileSizeNumber.int64Value)
        } catch _ as NSError {
            print("Filesize reading failed")
        }
        
        return fileSize/1024/1024
    }
    /**
     遍历所有子目录 并计算文件大小
     folderPaht: 目录路径
     返回文件总大小
     */
    private static func forderSizeAtPath(folderPath: String) -> Double {
        let manager = FileManager.default
        if !manager.fileExists(atPath: folderPath) {
            return 0
        }
        // 计算文件的大小
        var fileSize: Double = 0
        // 该文件下所有的子文件
        let childFilePath = manager.subpaths(atPath: folderPath)
        for path in childFilePath! {
            let fileAbsoluePath = folderPath + "/" + path
            fileSize += XCache.returnSingleFileSize(path: fileAbsoluePath)
        }
        return fileSize
    }

    /**
        删除单个文件
     */
    private static func deleteSingleFile(path:String){
        do {
            try FileManager.default.removeItem(atPath: path)
        } catch  {
            
        }
    }
    /**
     删除文件夹下面所有文件
     */
    private static func deleteFolder(folderPath: String) {
        let manage = FileManager.default
        let childFilePath = manage.subpaths(atPath: folderPath)
        for path in childFilePath! {
            let fileAbsoluePath = folderPath + "/" + path
            XCache.deleteSingleFile(path: fileAbsoluePath)
        }
    }
}

你可能感兴趣的:(swift计算目录缓存和清除操作)