19

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?

4

1 回答 1

13

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


在旁边

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

- (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. 创建对长缓存文件的请求。
  3. 检查 URL 是否存在响应并显示状态。
  4. 加载 URL。

首次加载时,您应该会看到“未找到缓存响应”。在随后的运行中,您将看到“找到缓存的响应!”

于 2013-08-26T21:37:18.687 回答