最近用swift语言做清除缓存,找了一圈,没什么合适的代码,有的教程还要搞个第三方包来清除缓存,个人表示有点无语了,不多说了,直接上代码。
计算缓存的方法,用于在画面显示。
func caculateCacheSize() -> String {
// 取出cache文件夹路径
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
// 打印路径,需要测试的可以往这个路径下放东西
// print(cachePath)
// 取出文件夹下所有文件数组
let files = FileManager.default.subpaths(atPath: cachePath!)
// 用于统计文件夹内所有文件大小
var big = Int();
// 快速枚举取出所有文件名
for p in files!{
// 把文件名拼接到路径中
let path = cachePath!.appendingFormat("/\(p)")
// 取出文件属性
let floder = try! FileManager.default.attributesOfItem(atPath: path)
// 用元组取出文件大小属性
for (abc,bcd) in floder {
// 只去出文件大小进行拼接
if abc == FileAttributeKey.size{
big += (bcd as AnyObject).integerValue
}
}
}
// 提示框
let message = "\(big/(1024*1024))M"
return message
}
清除缓存的事件,一般会有个alert
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 3 {
let cell = self.tableView.cellForRow(at: IndexPath.init(row: 3, section: 0))
// 缓存路径
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
// 取出文件夹下所有文件数组
let files = FileManager.default.subpaths(atPath: cachePath!)
// 提示框
let message = cell?.detailTextLabel?.text
let alert = UIAlertController(title: NSLocalizedString("Clear cache", comment: ""), message: message, preferredStyle: UIAlertController.Style.alert)
let alertConfirm = UIAlertAction(title: NSLocalizedString("Confirm", comment: ""), style: UIAlertAction.Style.default) { (alertConfirm) -> Void in
// 点击确定时开始删除
for p in files!{
// 拼接路径
let path = cachePath!.appendingFormat("/\(p)")
// 判断是否可以删除
if(FileManager.default.fileExists(atPath: path)){
// 删除
try! FileManager.default.removeItem(atPath: path)
}
}
cell!.detailTextLabel?.text = "0M"
}
alert.addAction(alertConfirm)
let cancle = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: UIAlertAction.Style.cancel) { (cancle) -> Void in
}
alert.addAction(cancle)
// 提示框弹出
self.present(alert, animated: true) {
}
}
}
OK,搞定。