前言
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ě)圖片描述