When we last left off from Part 1 , we saw that the server was telling our app not to cache responses. Normally one should respect the wishes of the server, but in this case I'm going to disobey. We're only given 1000 requests per hour, and it's unlikely the Photo of the Day is going to change.
In Part 1 we used
Charles to intercept the server responses to add the
and now we are going to do the same thing inside the app.
Set up the shared cache in
First we set up the shared cache to be our subclass of
NSURLCache with a
memory size of 30 MB and a disk size of 100 MB.
Every time one of our
NSURLSessionDataTask's from the singleton
NetworkClient successfully finishes,
called. Here we subclass
NSURLCache and override that method to inject the
Cache-Control header to the response header before calling the
We check to see if we can convert the
NSURLResponse to a
and if not, we exit before caching.
We check to see if we got a success status code, and if not exit before caching.
Here we grab the old headers, remove
Cache-Control if it exists, and then add
it back with a
max-age of one week.
We try to cast
headers to a
Dictionary of type
[String: String] and to
create a new
NSHTTPURLResponse. If both succeed, we
super to store the response.
This is all pretty straightforward, and the same thing we did in Part 1 with Charles.
Now when we run the app without intercepting responses with Charles, we see that refreshes do not cause our hourly API limit to decrease. If we clear the cache and then do a refresh, we do hit the server and our quota decreases.