ios 如何从 NSURLSessionTask 禁用缓存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24328461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:00:16  来源:igfitidea点击:

How to disable caching from NSURLSessionTask

ioscachingnsurlsessiontask

提问by Van Du Tran

In my iOS app, I am using NSURLSessionTaskto download json data to my app. I discovered that when I call the url directly from the browser, I get an up to date json and when it's called from within the app, I get an older version of the json.

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

Is this due to caching? How can I tell NSURLSessionTaskto not use caching.

这是由于缓存吗?我怎么知道NSURLSessionTask不使用缓存。

This is the call I use:

这是我使用的调用:

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

Thanks!

谢谢!

回答by Dave Haupert

If your read the links from @runmad you can see in the flow chart that if the HEAD of the file is unchanged it will still used the cached version when you set the cachePolicy.

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

In Swift3 I had to do this to get it to work:

在 Swift3 中,我必须这样做才能使其正常工作:

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

let session = URLSession.init(configuration: config)

That got a truly non-cached version of the file, which I needed for bandwidth estimation calculations.

这得到了文件的真正非缓存版本,我需要它来进行带宽估计计算。

回答by Rob

Rather than using the sharedSession, you also can create your own NSURLSessionusing a NSURLSessionConfigurationthat specifies a default cache policy. So, define a property for your session:

除了使用sharedSession,您还可以NSURLSession使用NSURLSessionConfiguration指定默认缓存策略的来创建自己的。因此,为您的会话定义一个属性:

@property (nonatomic, strong) NSURLSession *session;

And then:

进而:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
self.session = [NSURLSession sessionWithConfiguration:configuration];

Then requests using that session will use that requestCachePolicy.

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

回答by joliejuly

Swift 4.2

斯威夫特 4.2

I know it's been a while, but in case it might help someone in the future.

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

You may also use .ephemeralconfiguration property of URLSession, which doesn't save any cookies and caches by default.

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

As documentation goes,

随着文档的进行,

An ephemeral session configuration object is similar to a default session configuration, except that the corresponding session object doesn't store caches, credential stores, or any session-related data to disk. Instead, session-related data is stored in RAM.

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

So, your code might look like this:

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

let configuration = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: configuration)

回答by Gurjit Singh

Swift 3, Xcode 8

斯威夫特 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()
}

回答by anoop4real

The below code worked for me, the catch is setting URLCache to nil.

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

 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    config.URLCache = nil;

回答by Vinod Joshi

I was getting cache image for same url .. so i have done this

我正在获取相同 url 的缓存图像 .. 所以我已经做到了

imageView.imageFromUrl(self.shareData.userResponseData["photo"] as! String)

extension UIImageView {

public func imageFromUrl(urlString: String) {

    if let url = NSURL(string: urlString) {

        let request = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 60.0)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {

            (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            self.image = UIImage(data: data)

        }
    }
}

}

}

回答by runmad

You need to set the cachePolicyon NSURLRequest, here's the documentation.

您需要设置cachePolicyon NSURLRequest,这是文档

Here's some insight as to how caching worksin general.

这里有一些关于缓存一般如何工作的见解

You can read about the specific enums you can use for specifying the cachePolicyherein particular:

您可以阅读有关可用于在cachePolicy此处特别指定的特定枚举的信息

enum
{
   NSURLRequestUseProtocolCachePolicy = 0,
   NSURLRequestReloadIgnoringLocalCacheData = 1,
   NSURLRequestReturnCacheDataElseLoad = 2,
   NSURLRequestReturnCacheDataDontLoad = 3,
};
typedef NSUInteger NSURLRequestCachePolicy;

For example, you would do:

例如,你会这样做:

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];