如何从NSURLSessionTask禁用缓存

Van*_*ran 40 caching ios nsurlsessiontask

在我的iOS应用程序中,我NSURLSessionTask用来将json数据下载到我的应用程序.我发现当我直接从浏览器调用url时,我得到了一个最新的json,当它从应用程序中调用时,我得到了json的旧版本.

这是由于缓存?如何判断NSURLSessionTask不使用缓存.

这是我使用的电话:

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
Run Code Online (Sandbox Code Playgroud)

谢谢!

Dav*_*ert 50

如果您从@runmad中读取链接,则可以在流程图中看到,如果文件的HEAD未更改,则在设置cachePolicy时仍将使用缓存版本.

在Swift3中,我必须这样做才能让它工作:

let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil

let session = URLSession.init(configuration: config)
Run Code Online (Sandbox Code Playgroud)

这有一个真正的非缓存版本的文件,我需要进行带宽估算计算.


Rob*_*Rob 37

sharedSession您也可以NSURLSession使用NSURLSessionConfiguration指定默认缓存策略的方法创建自己的自己,而不是使用.因此,为您的会话定义一个属性:

@property (nonatomic, strong) NSURLSession *session;
Run Code Online (Sandbox Code Playgroud)

然后:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
self.session = [NSURLSession sessionWithConfiguration:configuration];
Run Code Online (Sandbox Code Playgroud)

然后使用该会话的请求将使用该请求requestCachePolicy.

  • 我看到我们还需要将`URLCache`设置为`nil` (2认同)

Gur*_*ngh 7

Swift 3,Xcode 8

extension UIImageView {
func donloadImage(fromUrl url: URL) {
    let request = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let image = UIImage(data: data)
            else { return }
        DispatchQueue.main.async() { () -> Void in
            self.image = image
        }
    }.resume()
}
Run Code Online (Sandbox Code Playgroud)


jol*_*uly 6

斯威夫特4.2

我知道已经有一段时间了,但以防万一将来可能对某人有所帮助。

您还可以使用的.ephemeral配置属性URLSession,默认情况下不会保存任何Cookie和缓存。

随着文档的发展,

临时会话配置对象类似于默认会话配置,不同之处在于相应的会话对象不将缓存,凭据存储或任何与会话相关的数据存储到磁盘。而是将与会话相关的数据存储在RAM中。

因此,您的代码可能如下所示:

let configuration = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: configuration)
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,我认为这仍然会存储这些东西,只是不存储到磁盘上。他们将在会话期间存活。要禁用 cookie,我必须设置 `sessionConfiguration.httpShouldSetCookies = false`。 (7认同)
  • 在 Swift 5 中工作 (4认同)

ano*_*eal 5

下面的代码对我有用,问题是将 URLCache 设置为 nil。

 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    config.URLCache = nil;
Run Code Online (Sandbox Code Playgroud)