swift清除缓存实例
2016-07-28 17:28
246 查看
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 }
相关文章推荐
- Apple Swift学习教程
- 页面缓存:内存和文件之间的那些事
- 介绍 Fedora 上的 Swift
- 交换机升级排障实例
- 浅析SQL Server中的执行计划缓存(上)
- Enterprise Library for .NET Framework 2.0缓存使用实例
- PowerShell中编程清空IE缓存方法
- PowerShell中使用.NET将程序集加入全局程序集缓存
- C#中缓存的基本用法总结
- sql2008启动代理未将对象应用到实例解决方案
- Android实现图片异步加载并缓存到本地
- wap开发中如何有效的利用缓存减少消息的传送量
- PHP基于文件存储实现缓存的方法
- smarty缓存用法分析
- 在ASP.NET 2.0中操作数据之五十九:使用SQL缓存依赖项SqlCacheDependency
- 在ASP.NET 2.0中操作数据之五十八:在程序启动阶段缓存数据
- 在ASP.NET 2.0中操作数据之五十七:在分层架构中缓存数据
- 引用全局程序集缓存内的程序集的方法
- asp Response.flush 实时显示进度