我有一个为URLCache
提供一些配置的类,我在寻找一种方法来手动清除缓存中存储的数据,以防长时间不使用该数据。
class DataCacher {
private var observer: NSObjectProtocol!
let defaultMaxMemoryLimit = 30
static var shared = DataCacher()
var sharedCache = URLCache()
init() {
didreceiveMemoryWarning()
URLCache.shared = sharedCache
}
init(maxMemoryLimit: Int) {
didreceiveMemoryWarning()
sharedCache = URLCache(
memoryCapacity: maxMemoryLimit*1024*1024,
diskCapacity: 0,
diskPath: nil
)
URLCache.shared = sharedCache
}
private func didreceiveMemoryWarning(){
observer = NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: nil, using: {_ in
self.sharedCache.removeAllCachedResponses()
})}
}