Search code examples
iosswiftcachingnsurlcache

iOS - How does caching work?


I am working on an app representing JSON from web API.

The remote source updates several times a day.

All I want to do is:

// pseudo code

makeRequest() {   
 if (network not available){

  if (cache not exists) {
      showEmptyScreen()
  }else if (cache exists){
      useCache()
  }

 }else if (network available){

    if (cache not exists) {   
        loadFromRemote()
    }else if (cache exists){
        if (cache is older than latest update) {
           loadFromrRemote()
        }else {
           useCache()
        }
    } 
 }
}

I've read about NSURLCache from Apple and from NSHipster.

It's still confusing that if NSURLCache could do what I want. For instance, how does it work to check if there's a newer version of data without really download anything?

And if NSURLCache could not handle the checking, how could I code it myself?

Thanks for any advice!


Solution

  • How caching behaves is mostly up to you and your server. NSURLCache does not make decisions on its own other than perhaps what to do when its capacity limit is exceeded.

    When you are making a request, headers like If-Modified-Since will determine if data is transferred or not by comparing the timestamps of the cached data.

    Server based headers such as Cache-Control can also affect how long data remains valid in the cache.

    In summary, NSURLCache can handle what you need but the implementation will be based on a combination of the configuration of NSURLCache, how you make requests, how cache control is implemented in responses and whether you override the policies given by the headers.