Swift计算app缓存与清理


1、计算缓存文件的大小

//Home目录

let homeDirectory = NSHomeDirectory()

let mydir1 = homeDirectory + "/Library/Caches"

do {

//声明文件管理器并初始化

let fileManager = NSFileManager.defaultManager()

//方法1

fileArray2?.removeAll()

fileArray2 = fileManager.subpathsAtPath(mydir1)

//获取数组里的文件的大小

for f in fileArray2! {

let attributes:NSDictionary = try fileManager.attributesOfItemAtPath(mydir1+"/\(f)")

let thefileSize:AnyObject!

thefileSize = attributes.objectForKey(NSFileSize)

let filesize = String(thefileSize)

let sizeint = Float(filesize)!/1024/1024

sizeM = sizeM + sizeint

}

let someM = String(format: "%.2f", sizeM)

//给label赋值

label.text = String(someM)+"MB"

}catch{}

2、清除缓存文件

//Home目录

lethomeDirectory =NSHomeDirectory()

letmydir1 = homeDirectory +"/Library/Caches"

//删除目录下所有文件

do{

letfileManager =NSFileManager.defaultManager()

//方法1

letfileArray2 : [AnyObject]? = fileManager.subpathsAtPath(mydir1)

//获取数组里的文件

forfinfileArray2! {

tryfileManager.removeItemAtPath(mydir1 +"/\(f)")

}

}catch{

}

你可能感兴趣的:(Swift计算app缓存与清理)