Caching anything in iOS

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

Raul Riera
iOS App Development

--

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…

--

--