swift 获取和删除缓存的功能,其实就是String的扩展功能使用如下的两个方法就可以实现
获取缓存和删除缓存的方法
在String中写入扩展
// 获取缓存
static func getCacheSize() -> String {
let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
let fileArr = FileManager.default.subpaths(atPath: cachePath!)
var size = 0
for file in fileArr! {
let path = cachePath! + "/\(file)"
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 String(format: "%.2f", totalCache)
}
//删除缓存
static func clearCache() {
let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
let fileArr = FileManager.default.subpaths(atPath: cachePath!)
for file in fileArr! {
let path = cachePath! + "/\(file)"
if FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.removeItem(atPath: path)
}catch {
}
}
}
}
网友评论