NSURLCache是​​否在发布期间持续存在? [英] Is NSURLCache persistent across launches?

查看:84
本文介绍了NSURLCache是​​否在发布期间持续存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的iOS应用程序寻找一种在发布过程中持久的网络缓存解决方案。我开始阅读有关NSURLCache的内容,但没有看到有关持久性的任何提及。当您使用NSURLCache然后关闭并打开应用程序时,是否有人知道这种行为?是否仍然存在?

I'm looking for a network caching solution for my iOS application that is persistent across launches. I started to read about NSURLCache, but didn't see any mention regarding persistence. Does anyone know how this behaves when you use NSURLCache then close and open the app? Does it persist?

推荐答案

NSURLCache 自动缓存对请求的请求根据服务器的缓存响应,缓存配置和请求的缓存策略, NSURLConnection UIWebView 。这些响应在缓存的生命周期内存储在内存和磁盘上。

NSURLCache automatically caches requests for requests made over NSURLConnection and UIWebViews according to the cache response from the server, the cache configuration, and the request's cache policy. These responses are stored in memory and on disk for the lifetime of the cache.

我使用以下代码验证了该行为。 您不需要在自己的代码中使用以下任何内容。这只是为了演示我如何确认行为。

I validated the behavior with the following code. You do not need to use any of the below in your own code. This is just to demonstrate how I confirmed the behavior.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Prime the cache.
    [NSURLCache sharedURLCache];
    sleep(1); // Again, this is for demonstration purposes only. I wouldn't do this in a real app.

    // Choose a long cached URL.
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://cdn.sstatic.net/stackoverflow/img/favicon.ico"]];

    // Check the cache.
    NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
    NSLog(cachedResponse ? @"Cached response found!" : @"No cached response found.");

    // Load the file.
    [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];

    return YES;
}

代码执行以下操作:


  1. 填充缓存。我注意到一种行为,缓存不会返回缓存的结果,直到缓存初始化并有机会扫描磁盘。

  2. 创建一个长缓存文件的请求。 / li>
  3. 检查URL是否存在响应并显示状态。

  4. 加载URL。

首次加载时,您应该看到未找到缓存响应。在后续运行中,您将看到已找到缓存响应!

On first load, you should see "No cached response found." On subsequent runs, you will see "Cached response found!"

这篇关于NSURLCache是​​否在发布期间持续存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆