Caching Over a Native Bridge

Published in Uken Games

Since taking over work on the native iOS framework that powers our applications, I haven’t actually been adding any new features. For the most part I have been trying to ensure that all of our applications are using the same version of the framework to make subsequent updates to the framework much more straightforward. For the last couple days though I have been working on adding a much requested feature to the framework which is adding capabilities to our web applications to cache and store data on the user’s device.

Web applications that run in a native wrapper are not known for being speed demons. This is generally because pages need to go off to the server get rendered, then return to the client device to be displayed. In an attempt to speed up this process, we want to be able to store data on the user’s device and retrieve it at a later date, which should be faster than requesting it from the server again.

While I was researching about how I was going to effectively cache the data on the native side, I came across a project from Tumblr called TMCache. It is a very cool parallel caching system that will not only cache in memory but will also persist the data to disk so that it can be retrieved even if the application is restarted. This seemed like a perfect fit for this project so I decided to use it. The next challenge is communicating from our javascript code to the native code to actually perform the caching (or retrieval). To do this, we are able to make an ajax request in javascript and actually intercept it on the native side. Once we intercept the request we can do anything we want including rendering and returning our own HTTP response.

Retrieving from the cache for a given key is a fairly easy process. We simply have to send the key as a parameter in our ajax request and then parse the parameter to look up the key in TMCache. Storing in the cache posed an interesting problem in its own right. Since we wanted to store a potentially large block of data (JSON), we could not simply send the data as a GET parameter in the URL. This meant that we needed to perform a POST request but upon doing this, the UIWebView was complaining about making a cross origin request and would not process fully. To satisfy the web view, I actually ended up injecting the proper CORS header (Access-Control-Allow-Origin: *) on the request and sending it back to the client. It is a little bit hacky but it worked wonders for our purposes.

Now our applications are able to store and retrieve JSON responses that don’t typically change too often. We have seen some nice performance gains in one of our new projects using this technique. I was ecstatic to get to work on this project as I learned a lot about some common ways that web-based applications can be given more of a native touch.


Written By

Andrew Halligan

Published October 13, 2013