如何清除URLSession / URLConfiguration存储的缓存数据?

时间:2017-06-17 09:34:28

标签: ios swift nsurlsession nsurlcache nscache

我正在使用以下代码通过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()

但这也不起作用。

1 个答案:

答案 0 :(得分:3)

有几点:

  • 将URL缓存设置为nil不会禁用所有缓存。用户仍然可以从代理中获取缓存数据。
  • 无法保证清除缓存是即时的。 IIRC,它滞后几秒钟。
  • 即使是即时的,用户仍然可以从代理中获取缓存数据。

简而言之,设置reloadIgnoringLocalCacheData是执行您正在做的事情的正确方法(嗯,真的,NSURLRequestReloadIgnoringLocalAndRemoteCacheData)。

但是,除非您尝试支持某种奇怪的离线模式,否则您可能想要使用returnCacheDataElseLoad。该模式忽略了服务器提供的缓存过期,您几乎肯定不想这样做。请改用默认策略(useProtocolCachePolicy)。