【问题标题】:Prevent NSURLSession from caching responses防止 NSURLSession 缓存响应
【发布时间】:2015-07-31 05:00:17
【问题描述】:

为什么它会缓存响应。它返回以前获取的响应。它甚至可以在关闭网络连接的情况下工作。重置 iOS 模拟器似乎也不起作用。发出请求,然后再次使用互联网离线确实有效(缓存)。

public let urlSession: NSURLSession

public init()
{
    // ...

    var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.requestCachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    urlSession = NSURLSession(configuration: configuration)
}

func makeRequest(path: String, httpMethod:String, body:String?, baseUrl: String?, headers:[String:String]=[:], callback: JsonRequestCallback)
{
    let urlString = (baseUrl ?? customOAuth2Manager.API_URL) + path
    let url = NSURL(string: urlString)
    let request = oauthInstance.request(forURL: url!)

    request.HTTPMethod = httpMethod
    self.customOAuth2Manager.setupRequest(request)

    for (key, value) in headers {
        request.setValue(value, forHTTPHeaderField:key)
    }

    if let body = body where body != "" {
        let postData = (body as NSString).dataUsingEncoding(NSUTF8StringEncoding)
        request.HTTPBody = postData
    }

    let task = urlSession.dataTaskWithRequest(request) { data, response, error in
        self.parseData(data, response:response, error:error, body:body, callback: callback)
    }
    task.resume()
}

更新

我设法通过在didFinishLaunching 中的AppDelegate 中调用此代码来解决它:

func removeUrlCache()
{
    NSURLCache.setSharedURLCache(NSURLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil))
}

但是,我仍然很好奇为什么我的原始代码不起作用。禁用所有应用程序的缓存来解决我的问题也感觉有点难看。

【问题讨论】:

  • 谢谢!!您是否发现了更多相关信息?
  • 在创建NSURLSessionConfiguration对象时将configuration.URLCache添加到nil,响应将不会被缓存。

标签: swift caching nsurlsession nsurlcache nsurlsessionconfiguration


【解决方案1】:

感谢您的提问。它让我走上了正确的道路。

NSURLCache.sharedURLCache() 有更多可能,您无需为此更改内存容量和磁盘容量。

您可以删除所有缓存的响应。 适合我。

URLCache.shared.removeAllCachedResponses()

或者您可以删除单个响应的缓存。 iOS 9 不适合我。

let request = URLRequest(url: URL(string: url)!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
    URLCache.shared.removeCachedResponse(for: request)

//Do your request here

希望对大家有所帮助!

编辑: 不幸的是,NSURLCache.sharedURLCache().removeCachedResponseForRequest(request) 不适合我

我的替代方案是:我正在使用它来拉取刷新,并且我正在跟踪上次更新日期。所以我使用了以下代码:

 URLCache.shared.removeCachedResponses(since: lateUpdate)

但由于某种原因,这无法正常工作。

从 iOS 8 开始,单个缓存删除方法似乎被破坏了:https://stackoverflow.com/a/26343653/2826164

2019-05-24,更新到 Swift 5。

【讨论】:

  • 我使用了另一种方法来删除特定请求的缓存响应,重置缓存响应,请参阅我在这篇文章中的回答stackoverflow.com/a/36507745/1080583
  • 你知道它在模拟器上的工作方式是否与实际设备不同吗?我使用了这种方法,在模拟器上,即使在调用 applicationWillResignActive 时删除所有缓存仍然会留下完整的 Cache.db 文件。
  • 我只在设备上测试过这个。您可以尝试清理 xCode 缓存,也许这会在 de 模拟器中给出不同的结果(清理 xCode 缓存 cmd+alt+shift+K)
【解决方案2】:

不确定这是否真的可以防止卡住或只是每次都强制重新加载,但这对我有用:

request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

这是一个屏幕截图,显示了其他选项,以防有人需要它们:

【讨论】:

    【解决方案3】:

    我将实现 URLSessionDelegate 并在 willCache 委托实现中使用 nil 调用 completionBlock。这是您的请求将永远不会受到影响

    【讨论】:

      【解决方案4】:

      选项 1 设置 sessionConfig.URLCache = nil 将禁用缓存。

      /* The URL resource cache, or nil to indicate that no caching is to be performed */
      @property (nullable, retain) NSURLCache *URLCache;
      

      后台会话中默认为 nil,因此默认情况下禁用缓存。

      参考:https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1410148-urlcache

      选项 2

      实现以下委托方法并调用 completionHandler(nil) 将阻止缓存。

      - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
                                        willCacheResponse:(NSCachedURLResponse *)proposedResponse 
                                        completionHandler:(void (^)(NSCachedURLResponse * _Nullable cachedResponse))completionHandler
      

      请注意,此委托方法仅在上传和数据任务时调用,不会为具有后台或临时配置的会话调用。

      参考:https://developer.apple.com/documentation/foundation/url_loading_system/accessing_cached_data

      【讨论】:

        猜你喜欢
        • 2014-11-23
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2012-04-13
        • 1970-01-01
        • 1970-01-01
        • 2018-02-03
        相关资源
        最近更新 更多