Mattress is a Swift framework for caching entire web pages for faster load times and offline use.
Here at BuzzFeed we are always looking for ways to improve our mobile app experience. One obvious step towards this goal is to decrease loading times as much as possible. Now, in most cases where you are simply pulling data down from an API and using that to populate your user interface, it's fairly straightforward. You can make a request to the API and retrieve and cache the data needed before it's needed for display.
However, what if your content is web based, being displayed in a standard web view? Additionally, what if you wanted this content to be available offline as well? This has traditionally been a much more difficult problem to solve. Enter Mattress — a Swift framework for caching entire web pages to disk.
Mattress is very easy to get started with, supporting both Carthage and CocoaPods for integration into your project. It also requires very little configuration, as it utilizes the hooks into the existing NSURLCache and NSURLProtocol system to provide UIWebView seamless access to cached content, both online and offline.
As is often the case, with great power comes great responsibility. As web pages are being fully rendered off screen, there is a non-trivial amount of processing power involved. While we have noticed minimal impacts on performance in most cases, it's good to keep this in mind and perform the caching at the most opportune time. Caching large amounts of content can also quickly eat up bandwidth, so you may want to change the level of caching based on whether a user is on wifi or utilizing cellular data. Fortunately, Mattress makes this easy to do.
One final limitation is that the newer WKWebView is currently not supported. This is an unfortunate consequence of how it interacts (or doesn't interact with) the standard NSURLCache and NSURLProtocol handlers.
We are currently using Mattress in the BuzzFeed News app and hope to see it in your app soon! We welcome any feedback and pull requests.
You can find it on Github here.