防止 NSURLSession 缓存响应

问题描述 投票:0回答:5

为什么它会缓存响应。它返回之前获取的响应。如果关闭网络连接它甚至可以工作。重置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))
}

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

swift caching nsurlsession nsurlcache nsurlsessionconfiguration
5个回答
21
投票

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

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。


13
投票

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

request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

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


1
投票

我将实现 URLSessionDelegate 并在 willCache 委托实现中调用带有 nil 的completionBlock。这是你的请求永远不会被满足


0
投票

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

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

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

参考: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


0
投票

使用 Swift 5,您只需指定缓存策略:

var urlRequest = URLRequest(url: myUrl)
urlRequest.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
© www.soinside.com 2019 - 2024. All rights reserved.