class func clearCache(finshed : (() -> Void)){
let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let files = NSFileManager.defaultManager().subpathsAtPath(cachePath[0])
let fileManager = NSFileManager.defaultManager()
for tempStr in files!{
let path = (cachePath.first! as NSString).stringByAppendingPathComponent(tempStr)
// 注释掉的下面的方法无效
echo("testExist:",NSFileManager.defaultManager().fileExistsAtPath(path))
do {
try fileManager.removeItemAtPath(path)
if tempStr == files?.last{
SVProgressHUD.showImage(nil, status: "清理完成")
finshed()
}
} catch let error as NSError{
if tempStr == files?.last{
SVProgressHUD.showImage(nil, status: "清理完成")
finshed()
}
echo("错误:",error.localizedDescription)
}
}
}
static var cacheSize: String{
get{
let basePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
let fileManager = NSFileManager.defaultManager()
func caculateCache() -> Float{
var total: Float = 0
if fileManager.fileExistsAtPath(basePath!){
let childrenPath = fileManager.subpathsAtPath(basePath!)
if childrenPath != nil{
for path in childrenPath!{
let childPath = basePath!.stringByAppendingString("/").stringByAppendingString(path)
do{
let attr = try fileManager.attributesOfItemAtPath(childPath)
let fileSize = attr["NSFileSize"] as! Float
total += fileSize
}catch _{
}
}
}
}
return total
}
let totalCache = caculateCache()
return NSString(format: "%.2fMB", totalCache / 1024.0 / 1024.0 ) as String
}
}
以上是Swift 2.3版本的方法,坑爹的来了,那就是Swift 3.0不认“NSFileSize”了。。。。
2.0系列中 fileManager.attributesOfItemAtPath(childPath) 返回的是[String : AnyObject]。
3.0系列中fileManager.attributesOfItemAtPath(childPath) 返回的是[FileAttributeKey : Any]