我正在为我的iOS应用程序寻找一种在发布过程中持久的网络缓存解决方案。我开始阅读有关NSURLCache的内容,但没有看到有关持久性的任何提及。当您使用NSURLCache然后关闭并打开应用程序时,是否有人知道这种行为?它会持续吗?
答案 0 :(得分:12)
NSURLCache
根据来自服务器的缓存响应,缓存配置和请求的缓存策略,自动缓存对NSURLConnection
和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;
}
代码执行以下操作:
首次加载时,您应该看到“未找到缓存响应”。在后续运行中,您将看到“已找到缓存响应!”