Swift3.0 清理緩存

最近的煩心事情不少,學習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的方法里即可。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,251評論 4 61
  • 三年了,自卑讓我備受煎熬; 一百多次血淚人生、一百多次開導、三百多篇反思日記還是沒辦法減輕我的孤獨和焦慮; 我不能...
    emerald_ying閱讀 222評論 0 1
  • 《復活》是托爾斯泰晚年最重要的作品,顯示了托爾斯泰“撕下一切假面具”的決心和徹底暴露舊世界的批判激情。小說對沙俄的...
    菡丹飛揚閱讀 710評論 0 0