Search code examples
iosfirebaseofflineoffline-cachingfirebasesimplelogin

How to persist Firebase objects to disk in iOS?


It seems that Firebase iOS implementation doesn't support offline caching of the client model. What this means in practice that:

  • For Firebase apps requiring an authentication, you need to first authenticate and wait Firebase finish the login (check the user identity, open a socket, etc.) before you can start moving the data. This will require 1-8 seconds (usually 2-5) depending on the network conditions, at least here in Finland.
  • After authenticating, Firebase first downloads the initial set of data and initializes the client cache. The time to perform this depends on the size of the data you add listeners for, but it's usually quite fast.

The problem here is that if you're using Firebase to implement, for example a messaging app, you'd most likely want to show the user a previously cached version of the message threads and messages, before the actual connection with the backend server is established.

I'd assume the correct implementation for this would need to handle:

  1. The client-side model <-> Firebase JSON mapping (I use Mantle for this)
  2. Persisting the client-side model to disk (manual implementation using NSKeyedArchiver, or Core Data or such?)
  3. Synchronizing the on-disk model with the Firebase-linked model in memory, when the connection is available (manual implementation?)

Has anyone come up with a solution (own or 3rd party) to achieve 2) and 3)?


Solution

  • It seems Firebase has solved this problem since this question was asked. There are a lot of resources on Offline Capabilities now with Firebase, including disk persistence.

    For me, turning on persistence was as simple as the following in my AppDelegate:

    Firebase.defaultConfig().persistenceEnabled = true
    

    Assuming your app has been run with an internet connection at least once, this should work well in loading the latest local copy of your data.