swift清除缓存实例
【swift清除缓存实例】博客:http://blog.csdn.net/zyfmeng/article/details/52057263
overridefunc viewDidLoad() {super.viewDidLoad()
let btn =UIButton.init(type:UIButtonType.RoundedRect)
btn.frame =CGRectMake(100,100, 100,50)
btn.setTitle("清除缓存", forState:UIControlState.Normal)
btn.addTarget(self, action:#selector(clearCacheBtnClick), forControlEvents:UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
}
func clearCacheBtnClick(sender:UIButton){
print(sender.tag)
//提示框
let message =self.caculateCache()
let alert =UIAlertController(title: "清除缓存", message: message, preferredStyle:UIAlertControllerStyle.Alert)
let alertConfirm =UIAlertAction(title: "确定", style:UIAlertActionStyle.Default) { (alertConfirm) ->Void in
self.clearCache()
}
alert.addAction(alertConfirm)
let cancle =UIAlertAction(title: "取消", style:UIAlertActionStyle.Cancel) { (cancle) ->Void in
}
alert.addAction(cancle)
//提示框弹出
presentViewController(alert, animated:true) { () -> Voidin}
}
//计算缓存大小func caculateCache() ->String{
let basePath =NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory,NSSearchPathDomainMask.UserDomainMask,true).first
let fileManager =NSFileManager.defaultManager()
print("cache= \(basePath)")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_{}
}
}
}let cacheSize =NSString(format: "%.1f MB缓存", total /1024.0 / 1024.0 )as String
return cacheSize
}//清除缓存
func clearCache() ->Bool{
var result =true
let basePath =NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory,NSSearchPathDomainMask.UserDomainMask,true).first
print("cache= \(basePath)")
let fileManager =NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(basePath!){
let childrenPath = fileManager.subpathsAtPath(basePath!)
for childPathin childrenPath!{
let cachePath = basePath?.stringByAppendingString("/").stringByAppendingString(childPath)
do{
try fileManager.removeItemAtPath(cachePath!)
}catch_{
result =false
}
}
}return result
}
推荐阅读
- 不废话,代码实践带你掌握|不废话,代码实践带你掌握 强缓存、协商缓存!
- Swift中willSet和didSet的简述
- Hacking|Hacking with iOS: SwiftUI Edition - SnowSeeker 项目(一)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- 15、IDEA学习系列之其他设置(生成javadoc、缓存和索引的清理等)
- springboot使用redis缓存
- 缓存有关的配置和属性
- iOS-Swift-map|iOS-Swift-map filter reduce、函数式编程
- Swift|Swift ----viewController 中addChildViewController
- SwiftUI|SwiftUI iOS 瀑布流组件之仿CollectionView不规则图文混合(教程含源码)