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清除缓存实例)