ios swift 计算文件夹大小以及清除缓存文件

//
//  XCache.swift
//  UITablViewTest
//
//  Created by Marcio on 2017/2/14.
//  Copyright © 2017年 Marcio. All rights reserved.
//

import UIKit

class XCache: NSObject {
    
    /**
     * 读取缓存大小
     */
    static func returnCacheSize() -> String {
        return String(format: "%.2f",XCache.forderSizeAtPath(folderPath: NSHomeDirectory()))
    }
    
    /**
     * 清除缓存 自己决定清除缓存的位置
     */
    static func cleanCache(competion:()->Void) {
        XCache.deleteFolder(path: NSHomeDirectory() + "/Documents")
        XCache.deleteFolder(path: NSHomeDirectory() + "/Library")
        XCache.deleteFolder(path: NSHomeDirectory() + "/tmp")
        competion()
    }
    /**
     * 删除单个文件
     */
    static func deleteFile(path: String) {
        let manage = FileManager.default
        do {
            try manage.removeItem(atPath: path)
        } catch {
            
        }
    }
    
    static func deleteFolder(path: String) {
        let manage = FileManager.default
        if !manage.fileExists(atPath: path) {
        }
        let childFilePath = manage.subpaths(atPath: path)
        for path_1 in childFilePath! {
            let fileAbsoluePath = path+"/"+path_1
            XCache.deleteFile(path: fileAbsoluePath)
        }
    }
    
    /**
     * 计算单个文件的大小
     */
    static func returnFileSize(path:String) -> Double {
        let manager = FileManager.default
        var fileSize:Double = 0
        do {
            let attr = try manager.attributesOfItem(atPath: path)
            fileSize = Double(attr[FileAttributeKey.size] as! UInt64)
            let dict = attr as NSDictionary
            fileSize = Double(dict.fileSize())
        } catch {
            dump(error)
        }
        return fileSize/1024/1024
    }
    
    /**
     * 遍历所有子目录, 并计算文件大小
     */
    static func forderSizeAtPath(folderPath:String) -> Double {
        let manage = FileManager.default
        if !manage.fileExists(atPath: folderPath) {
            return 0
        }
        let childFilePath = manage.subpaths(atPath: folderPath)
        var fileSize:Double = 0
        for path in childFilePath! {
            let fileAbsoluePath = folderPath+"/"+path
            fileSize += XCache.returnFileSize(path: fileAbsoluePath)
        }
        return fileSize
    }

}

 

posted @ 2017-02-15 17:17  MaricoSun  阅读(2392)  评论(0编辑  收藏  举报