最近的煩心事情不少,學習Swift之路就這么慢了下來。10月底,朋友說想要一個可以看嘿嘿的電影的APP。剛好在學Swift,就嘗試著用Swift去開發一款。功能已經實現,但由于能力有限,很多東西是用的第三方,如播放功能。昨天寫完朋友讓給添加一個清除緩存的功能,說圖片占的太大,所以只好找找OC的,然后用Swift改。。。
1.找到緩存的路徑
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
路徑結果:/Users/用戶名/Library/Developer/CoreSimulator/Devices/C8543F66-393F-4174-A12D-1BD99E1F8141/data/Containers/Data/Application/6DE40038-25AE-4D82-900E-DED0C76DDE50/Library/Caches
如圖就是路徑的位置了
在Finder中按command+shift+G后粘貼要去的位置即可。
2.計算內存大小
let files = FileManager.default.subpaths(atPath:cachePath)
// 統計文件夾內所有文件大小
var total = 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{
total += (bcd as AnyObject).integerValue
}
}
}
let message = "\(total/(1000*1000))M緩存"
3.清除緩存
let files = FileManager.default.subpaths(atPath:cachePath)
let alert = UIAlertController(title: "清除緩存", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "確定", style: UIAlertActionStyle.default) { (alertConfirm) -> Void in
// 點擊確定->刪除
for p in files!{
// 拼接路徑
let path = self.cachePath.appendingFormat("/\(p)")
// 判斷是否可以刪除
if(FileManager.default.fileExists(atPath: path)){
// 刪除
try! FileManager.default.removeItem(atPath: path)
}
}
})
alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (cancle) -> Void in
print("用戶點擊取消")
})
// 彈出提示框
present(alert, animated: true, completion: nil)
以上放進一個button的方法里即可。