我正在使用以下代码通过URLConfiguration设置我的URLSession的缓存策略。
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)
我遇到的问题是,即使在设置
后,我也会收到缓存的响应appDelegateObj.configuration?.urlCache = nil
我能够获取新数据的唯一方法是使用
appDelegateObj.configuration?.requestCachePolicy = .reloadIgnoringLocalCacheData
我做错了什么?我需要一种方法来清除应用程序的所有缓存数据。
我尝试过使用
URLCache.shared.removeAllCachedResponses()
但这也不起作用。
答案 0 :(得分:3)
有几点:
简而言之,设置reloadIgnoringLocalCacheData
是执行您正在做的事情的正确方法(嗯,真的,NSURLRequestReloadIgnoringLocalAndRemoteCacheData
)。
但是,除非您尝试支持某种奇怪的离线模式,否则您可能不想要使用returnCacheDataElseLoad
。该模式忽略了服务器提供的缓存过期,您几乎肯定不想这样做。请改用默认策略(useProtocolCachePolicy
)。