DamusCacheManager.swift (2157B)
1 // 2 // DamusCacheManager.swift 3 // damus 4 // 5 // Created by Daniel D’Aquino on 2023-10-04. 6 // 7 8 import Foundation 9 import Kingfisher 10 11 struct DamusCacheManager { 12 static var shared: DamusCacheManager = DamusCacheManager() 13 14 func clear_cache(damus_state: DamusState, completion: (() -> Void)? = nil) { 15 Log.info("Clearing all caches", for: .storage) 16 clear_kingfisher_cache(completion: { 17 clear_cache_folder(completion: { 18 Log.info("All caches cleared", for: .storage) 19 completion?() 20 }) 21 }) 22 } 23 24 func clear_kingfisher_cache(completion: (() -> Void)? = nil) { 25 Log.info("Clearing Kingfisher cache", for: .storage) 26 KingfisherManager.shared.cache.clearMemoryCache() 27 KingfisherManager.shared.cache.clearDiskCache { 28 Log.info("Kingfisher cache cleared", for: .storage) 29 completion?() 30 } 31 } 32 33 func clear_cache_folder(completion: (() -> Void)? = nil) { 34 Log.info("Clearing entire cache folder", for: .storage) 35 let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] 36 37 do { 38 let fileNames = try FileManager.default.contentsOfDirectory(atPath: cacheURL.path) 39 40 for fileName in fileNames { 41 let filePath = cacheURL.appendingPathComponent(fileName) 42 43 // Prevent issues by double-checking if files are in use, and do not delete them if they are. 44 // This is not perfect. There is still a small chance for a race condition if a file is opened between this check and the file removal. 45 let isBusy = (!(access(filePath.path, F_OK) == -1 && errno == ETXTBSY)) 46 if isBusy { 47 continue 48 } 49 50 try FileManager.default.removeItem(at: filePath) 51 } 52 53 Log.info("Cache folder cleared successfully.", for: .storage) 54 completion?() 55 } catch { 56 Log.error("Could not clear cache folder", for: .storage) 57 } 58 } 59 }