Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NSURLCache persistent across launches?

Tags:

ios

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?

like image 515
Brandon Avatar asked Aug 26 '13 19:08

Brandon


People also ask

What is NSURLCache?

The NSURLCache class implements the caching of responses to URL load requests, by mapping NSURLRequest objects to NSCachedURLResponse objects. It provides a composite in-memory and on-disk cache, and lets you manipulate the sizes of both the in-memory and on-disk portions.

What is Nscache in iOS?

A mutable collection you use to temporarily store transient key-value pairs that are subject to eviction when resources are low. iOS 4.0+ iPadOS 4.0+ macOS 10.6+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+


1 Answers

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.


Aside

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;
}

The code does the following:

  1. Primes the cache. I noticed a behavior where the cache would not return the cached result until the cache had been initialized and had a chance to scan the disk.
  2. Creates a request for a long-cached file.
  3. Checks if a response exists for the URL and displays the status.
  4. Loads the URL.

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

like image 155
Brian Nickel Avatar answered Oct 15 '22 15:10

Brian Nickel