Swift之缓存文件处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Forever_wj/article/details/73467453
//
//  YDWCache.swift
//  Project
//
//  Created by cptech on 2017/6/19.
//  Copyright © 2017年 CPTECH_ydw. All rights reserved.
//

import UIKit

class YDWCache: NSObject {

    /**
     * 以NSHomeDirectory()为例
     */

    // 读取缓存的大小
    static func returnCacheSize()->String {
        return String(format:"%.2f",forderSizeAtPath(folderPath: NSHomeDirectory()))
    }

    // 根据文件的路径计算文件的大小(MB)
    static func returnFileSize(path:String)->Double {
        let fileManager = FileManager.default
        var fileSize:Double = 0
        do {
            fileSize = Double(try fileManager.attributesOfItem(atPath: path)[FileAttributeKey.size] as! UInt64)
            fileSize = Double((try fileManager.attributesOfItem(atPath: path) as NSDictionary).fileSize())
        } catch {
            dump(error)
        }
        return fileSize/1024.0/1024.0
    }

    // 遍历文件的子目录,计算文件的大小
    static func forderSizeAtPath(folderPath:String)->Double {
        let filemanager = FileManager.default
        if !filemanager.fileExists(atPath: folderPath) {
            return 0
        }
        let childFilePath = filemanager.subpaths(atPath: folderPath)
        var fileSize:Double = 0
        for path in childFilePath! {
            let fileAbsoluePath = folderPath+"/"+path
            fileSize += YDWCache.returnFileSize(path: fileAbsoluePath)
        }
        return fileSize
    }

    // 清除缓存
    static func cleanCache(competion:()->Void) {
        YDWCache.deleteFolder(folderPath: NSHomeDirectory() + "/Documents")
        YDWCache.deleteFolder(folderPath: NSHomeDirectory() + "/Library")
        YDWCache.deleteFolder(folderPath: NSHomeDirectory() + "/tmp")

        competion()
    }

    // 删除单个文件
    static func deleteFile(path:String) {
        let fileManager = FileManager.default
        do {
            try fileManager.removeItem(atPath: path)
        } catch {
            dump(error)
        }
    }

    // 删除文件下的所有文件
    static func deleteFolder(folderPath:String) {
        let fileManager = FileManager.default
        if !fileManager.fileExists(atPath: folderPath) {

        }
        let childFilePath = fileManager.subpaths(atPath: folderPath)
        for path in childFilePath! {
            let fileAbsoluePath = folderPath+"/"+path
            YDWCache.deleteFile(path: fileAbsoluePath)
        }
    }

}

猜你喜欢

转载自blog.csdn.net/Forever_wj/article/details/73467453