Offline Data Caching
If the users of your app may need to use it in areas of low or no network coverage (for example in remote rural areas) then you may want to consider implementing caching data for offline use. In this guide we will outline the general approach and different ways to achieve this on iOS and Android.
The general approach to caching data locally for offline use is as follows:
- On app startup and/or the loading of each screens' data, check the local cache...
- If data is found in the cache, load it the data, populate UI then initiate a Kumulos request to get latest data
- If no data is found, initiate the Kumulos request to get the latest data
- In the Kumulos result handler, update your local cache and notify the UI
- Reload any UI data with the new data from local cache
You can add various optimisations to this depending on your use case.
- Run an asynchronous task to refresh local cache periodically.
- Evict old data from the local cache after a certain time period.
- Record the time of the last 'sync' and only requesting things that have changed since that time from Kumulos using the timeCreated and timeUpdated magic fields.
Depending on the nature of your data, you could implement this in one of two ways:
- A cache for each different data model/screen of your app, specific to that data model
- A generic cache for any Kumulos result data that you store serialised as JSON or similar, and identify by a combination (for example md5 hash) of the method name and the parameters that were passed to the method.
Each of those approaches has various trade-offs in terms of complexity vs. time to implement a cache for each method. If you have relatively few data models, option 1 will be simpler, but if you have many different models, option 2 could be a little quicker, although slightly more complex to implement (for example as you may have to ignore certain time or location based parameters).
To implement this in iOS, you will need to use Core Data to store and load the local cache data.
To implement this in Android, you will need:
- ContentProvider to store your local data
- Loaders / ContentResolvers to read the local cache
- The SyncAdapter if you want to load the data in the background periodically
You may wish to look into Realm, which provides an alternate data store for mobile devices that can in some cases be simpler to work with than the native data stores (particularly on Android). It would also be consistent across platforms.