Swift3.0 清理緩存

最近的煩心事情不少,學(xué)習(xí)Swift之路就這么慢了下來。10月底,朋友說想要一個(gè)可以看嘿嘿的電影的APP。剛好在學(xué)Swift,就嘗試著用Swift去開發(fā)一款。功能已經(jīng)實(shí)現(xiàn),但由于能力有限,很多東西是用的第三方,如播放功能。昨天寫完朋友讓給添加一個(gè)清除緩存的功能,說圖片占的太大,所以只好找找OC的,然后用Swift改。。。

1.找到緩存的路徑

let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
路徑結(jié)果:/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.計(jì)算內(nèi)存大小


let files = FileManager.default.subpaths(atPath:cachePath)
        // 統(tǒng)計(jì)文件夾內(nèi)所有文件大小
        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 {
                // 只去出文件大小進(jìn)行拼接
                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
            // 點(diǎn)擊確定->刪除
            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("用戶點(diǎn)擊取消")
            })
        // 彈出提示框
       present(alert, animated: true, completion: nil)      

以上放進(jìn)一個(gè)button的方法里即可。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容