场景:最近项目需求迭代,需要加一个清除APP缓存的入口
缓存文件大小的获取(Swift5.0版本):
/// 获取缓存大小
class func getCacheSize() -> Double {
/// 本地沙盒目录下的缓存
// 取出cache文件夹目录
guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
return 0
}
// 取出文件夹下所有文件数组
let fileArr = FileManager.default.subpaths(atPath: cachePath) ?? []
guard fileArr.count > 0 else {
return 0
}
//快速枚举出所有文件名 计算文件大小
var size = 0
for file in fileArr {
// 把文件名拼接到路径中
let path = cachePath + ("/\(file)")
// 取出文件属性
if let floder = try? FileManager.default.attributesOfItem(atPath: path) {
// 用元组取出文件大小属性
for (key, fileSize) in floder {
// 累加文件大小
if key == FileAttributeKey.size {
size += (fileSize as AnyObject).integerValue
}
}
}
}
let totalCache = Double(size) / 1024.00 / 1024.00
return totalCache
}
清除缓存:
/// 清除缓存
class func clearCache(with completion: ((Double)->())?) {
HUD.show()
// 取出cache文件夹目录
if let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first {
let fileArr = FileManager.default.subpaths(atPath: cachePath) ?? []
guard fileArr.count > 0 else {
HUD.dismiss()
completion?(0)
return
}
// 遍历删除
for file in fileArr {
let path = (cachePath as NSString).appending("/\(file)")
if FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.removeItem(atPath: path)
} catch {
}
}
}
HUD.dismiss()
let DoubleSize = CacheManager.getCacheSize()
completion?(DoubleSize)
} else {
HUD.dismiss()
completion?(0)
}
}
网友评论