如何清除URLSession/URLConfiguration存储的缓存数据? [英] How to clear cached data stored by URLSession/URLConfiguration?
问题描述
我正在使用以下代码通过URLConfiguration设置URLSession的缓存策略.
I am using the code below to set the caching policy of my URLSession via URLConfiguration.
if appDelegateObj.configuration == nil {
appDelegateObj.configuration = URLSessionConfiguration.default
}
if self.apiType == ServerRequest.API_TYPES_NAME.API1 {
if appDelegateObj.forceReload == true {
appDelegateObj.configuration?.urlCache = nil
appDelegateObj.configuration?.requestCachePolicy = .reloadIgnoringLocalCacheData
}else{
appDelegateObj.configuration?.requestCachePolicy = .returnCacheDataElseLoad
}
}else{
appDelegateObj.configuration?.requestCachePolicy = .reloadIgnoringLocalCacheData
}
session = URLSession(configuration: appDelegateObj.configuration!, delegate: nil, delegateQueue: nil)
我遇到的问题是,即使在设置
The problem I am having is that I am getting the cached response back even after setting the
appDelegateObj.configuration?.urlCache = nil
我能够获取最新数据的唯一方法是使用
The only way I am able to get fresh data is via using
appDelegateObj.configuration?.requestCachePolicy = .reloadIgnoringLocalCacheData
我在做什么错?我需要一种方法来清除该应用程序的所有缓存数据.
What am I doing wrong ? I need a way to clear all the cached data for the app.
我尝试使用
URLCache.shared.removeAllCachedResponses()
但是那也不起作用.
推荐答案
几点:
- 将URL缓存设置为nil不会禁用所有缓存.用户仍然可以从代理获取缓存的数据.
- 不能保证清除缓存是即时的. IIRC,它滞后了几秒钟.
- 即使是即时的,用户仍然可以从代理获取缓存的数据.
简而言之,设置reloadIgnoringLocalCacheData
是做您正在做的事情的正确方法(嗯,真的,NSURLRequestReloadIgnoringLocalAndRemoteCacheData
).
In short, setting reloadIgnoringLocalCacheData
is the correct way to do what you're doing (well, really, NSURLRequestReloadIgnoringLocalAndRemoteCacheData
).
但是,除非您尝试支持某些奇怪的脱机模式,否则可能不想要使用returnCacheDataElseLoad
.该模式将忽略服务器提供的缓存过期,您几乎肯定不希望这样做.请改用默认策略(useProtocolCachePolicy
).
However, unless you're trying to support some weird offline mode, you probably do not want to be using returnCacheDataElseLoad
. That mode ignores the cache expiration provided by the server, which you almost certainly do not want to do. Use the default policy (useProtocolCachePolicy
) instead.
这篇关于如何清除URLSession/URLConfiguration存储的缓存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!