*** 清空缓存
//清除 Library/Caches func clearCaches(){ do { try deleteLibraryFolderContents(folder: "Caches") //print("clear done") } catch { //print("clear Caches Error") } } // private func deleteLibraryFolderContents(folder: String) throws { let manager = FileManager.default let library = manager.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask)[0] let dir = library.appendingPathComponent(folder) let contents = try manager.contentsOfDirectory(atPath: dir.path) for content in contents { //如果是快照就继续 if(content == "Snapshots"){continue;} do { try manager.removeItem(at: dir.appendingPathComponent(content)) //print("remove cache success:"+content) } catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) { //print("remove cache error:"+content) // "EPERM: operation is not permitted". We ignore this. #if DEBUG //print("Couldn't delete some library contents.") #endif } } }
** 统计缓存大小
var fileSize:Int = 0; override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(false) UIView.animate(withDuration: 0.3, animations: {() -> Void in self.v.frame.origin.y = 0; }){(finished) -> Void in DispatchQueue.global().async { self.fileSize = self.fileSizeOfCache(); //获取数据异步 DispatchQueue.main.async { //修改主线程UI self.clearLable.text = "已用 "+String(self.fileSize)+" MB"; } } } }
//获取缓存大小 func fileSizeOfCache()-> Int { // 取出cache文件夹目录 缓存文件都在这个目录下 let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first //缓存目录路径 //print(cachePath) // 取出文件夹下所有文件数组 let fileArr = FileManager.default.subpaths(atPath: cachePath!) //快速枚举出所有文件名 计算文件大小 var size = 0 for file in fileArr! { // 把文件名拼接到路径中 let path = cachePath?.appending("/\(file)") // 取出文件属性 let floder = try! FileManager.default.attributesOfItem(atPath: path!) // 用元组取出文件大小属性 for (abc, bcd) in floder { // 累加文件大小 if abc == FileAttributeKey.size { size += (bcd as AnyObject).integerValue } } } let mm = size / 1024 / 1024 return mm }
相关推荐
Swift-获取app缓存大小
WHC_Model iOS平台高效转换引擎json->model,model->json,model->Dictionary,支持模型类继承其他模型类,支持指定路径转换,不区分json的key和模型属性名称大小写,自动处理json中null。
NULL 博文链接:https://mft.iteye.com/blog/2310507
在项目中经常需要做清除缓存的功能,但是很可能没有考虑全面,造成一些BUG,这里写了一个比较全面的清除缓存功能
iOS-Swift-清除缓存,我整理出来的资源
Yahoo开源的在线obj-c -> swift工具
NULL 博文链接:https://mft.iteye.com/blog/2304029
NULL 博文链接:https://mft.iteye.com/blog/2343765
NULL 博文链接:https://mft.iteye.com/blog/2428573
NULL 博文链接:https://mft.iteye.com/blog/2296790
NULL 博文链接:https://mft.iteye.com/blog/2310323
NULL 博文链接:https://mft.iteye.com/blog/2313269
NULL 博文链接:https://mft.iteye.com/blog/2296699
NULL 博文链接:https://mft.iteye.com/blog/2297851
NULL 博文链接:https://mft.iteye.com/blog/2343587
Swift-单例Swift-单例Swift-单例Swift-单例Swift-单例
swift-request:声明式HTTP网络,专为SwiftUI设计
Cache.swift - 一款简单、易用的缓存库。支持 MemoryCache, DiskCache 以及前两项组合的 MultiCache。
Swift-Radio-Pro:完整的Swift 2.0的App 开源应用