iOS-Swift-清理緩存

前言

swift現(xiàn)在網(wǎng)上資源比較亂,需要找的要找很久,于是自己開(kāi)始整理自己遇到的功能開(kāi)始swift化,如果效果不錯(cuò)的話以后就會(huì)一直發(fā)表swift的博客,所以請(qǐng)各位讀者多給我的GitHub點(diǎn)幾個(gè)Star吧!


效果圖

這里寫(xiě)圖片描述

上代碼

在storyBoard創(chuàng)建一個(gè)button關(guān)聯(lián)點(diǎn)擊事件,然后在ViewController里寫(xiě)上以下代碼

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
}

@IBAction func alertAction(sender: UIButton) {
    // 取出cache文件夾路徑
    let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
    // 打印路徑,需要測(cè)試的可以往這個(gè)路徑下放東西
    print(cachePath)
    // 取出文件夾下所有文件數(shù)組
    let files = NSFileManager.defaultManager().subpathsAtPath(cachePath!)
    // 用于統(tǒng)計(jì)文件夾內(nèi)所有文件大小
    var big = Int();
    
    
    // 快速枚舉取出所有文件名
    for p in files!{
        // 把文件名拼接到路徑中
        let path = cachePath!.stringByAppendingFormat("/\(p)")
        // 取出文件屬性
        let floder = try! NSFileManager.defaultManager().attributesOfItemAtPath(path)
        // 用元組取出文件大小屬性
        for (abc,bcd) in floder {
            // 只去出文件大小進(jìn)行拼接
            if abc == NSFileSize{
                big += bcd.integerValue
            }
        }
    }
    
    // 提示框
    let message = "\(big/(1024*1024))M緩存"
    let alert = UIAlertController(title: "清除緩存", message: message, preferredStyle: UIAlertControllerStyle.Alert)
    
    let alertConfirm = UIAlertAction(title: "確定", style: UIAlertActionStyle.Default) { (alertConfirm) -> Void in
        // 點(diǎn)擊確定時(shí)開(kāi)始刪除
        for p in files!{
            // 拼接路徑
            let path = cachePath!.stringByAppendingFormat("/\(p)")
            // 判斷是否可以刪除
            if(NSFileManager.defaultManager().fileExistsAtPath(path)){
                // 刪除
                try! NSFileManager.defaultManager().removeItemAtPath(path)
            }
        }
    }
    alert.addAction(alertConfirm)
    let cancle = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel) { (cancle) -> Void in
        
    }
    alert.addAction(cancle)
    // 提示框彈出
    presentViewController(alert, animated: true) { () -> Void in
        
    }
}

效果展示

這里寫(xiě)圖片描述

GitHub:https://github.com/Lafree317/ClearCache-Swift

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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