您的位置:首页 > 移动开发 > Swift

Swift之缓存文件处理

2017-06-19 14:42 176 查看
//
//  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)
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息