Caching anything in iOS

In a world filled with JSON fetching apps, caching is king.

Most iOS apps are asking a server for some JSON data, transforming it and present it nicely to the user. Caching these JSON responses can be achieved with headers and the built in functionality in URLSession.

Recently, I faced a problem that I needed to cache the request instead of the response. I needed to store upload files in the background and enable the system to restore the file and information.

Turning to Protocols… 🙄 here we go again

They certainly are not a silver bullet, but in this case it was exactly what I needed. My requirement was simple enough, I needed something that can cache any type of data. Which translated into this:

public protocol Cachable {
var fileName: String { get }
func transform() -> Data
}

This simple protocol ensures that all the types conforming to it have a filename property and a method that transforms itself into Data, which is all the information we need to write something into the filesystem.

Now that we have this file, we can have CachableText, CachableImage, CachableDictionary. You get the idea 😉.

Caching the Cachables

Now that the types were created, it was only a matter or creating a file that takes Cachable Types and persistent them in the filesystem. Taking inspiration from the Ice Cream builder source code from WWDC, the Cacher looks like this.

The important part is the only method in the file persist which takes in the Cachable type uses the transform method to write to the disk and returns the location back to me.


That is it! With Cacher.swift and Cachable.swift now anything in the app can be stored in the filesystem and retrieved later, without actually hard coding it for file uploads like the initial requirement.

Get in touch on Twitter: @raulriera

Update:

For the full implementation and framework support, check out https://github.com/raulriera/Cacher 🎉