Swift中URLSession如何禁用本地缓存强制拉取服务端最新数据
问题根因
你自定义的URLSessionConfiguration缓存相关配置没有生效,是因为你没有使用该配置创建独立的URLSession实例,而是直接使用了全局共享的URLSession.shared,该实例默认使用系统级的默认配置,不会读取你本地修改的configuration参数。
正确解决方案
有两种常用的实现方式,任选一种即可:
方案1:为单个请求单独设置缓存策略(不需要修改Session配置)
直接在创建URLRequest时指定缓存策略,优先级高于Session的全局配置,适合仅部分请求需要禁用缓存的场景:
@IBAction func urlButtonClick(_ sender: Any) { let url = URL(string:"https://www.someserver.com/info.txt")! // 自定义请求,指定缓存策略 var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10) // 这里即使使用shared session也会生效 let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in if let error = error { print(error) return } guard let data = data, let textFile = String(data: data, encoding: .ascii) else { return } print(textFile) DispatchQueue.main.async { self.textLabel.text = textFile } }) task.resume() }
方案2:使用自定义配置创建独立URLSession
如果该Session下所有请求都需要禁用缓存,就用你修改后的配置创建新的Session实例即可:
@IBAction func urlButtonClick(_ sender: Any) { let configuration = URLSessionConfiguration.default configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData configuration.urlCache = nil // 用自定义配置创建session,不要用shared let customSession = URLSession(configuration: configuration) let url = URL(string:"https://www.someserver.com/info.txt")! let task = customSession.dataTask(with: url, completionHandler: { data, response, error in if let error = error { print(error) return } guard let data = data, let textFile = String(data: data, encoding: .ascii) else { return } print(textFile) DispatchQueue.main.async { self.textLabel.text = textFile } }) task.resume() // 注意:如果不需要复用自定义session,请求完成后可以调用invalidateAndCancel释放资源 }
补充说明:优先使用
.reloadIgnoringLocalAndRemoteCacheData而非.reloadIgnoringLocalCacheData,前者会完全忽略本地和中间代理的所有缓存,强制从源服务器拉取最新数据,完全符合你的需求。
内容的提问来源于stack exchange,提问作者opticalbot
相关产品推荐
相关产品推荐

