jamryu
jamryu

Reputation: 698

Is there a way to enable offline persistence for only one collection, but not other collection?

I have two collections set up in my Firestore database:

let COLLECTION_POSTS = Firestore.firestore().collection("posts")
let COLLECTION_USERS = Firestore.firestore().collection("users")

In COLLECTION_POSTS, users' social posts (e.g. Facebook-style post) will be saved. It can have pictures, so I would not want to let these posts be cached locally. However, I would allow data from COLLECTION_USERS be cached. It does not take up much space in hard drive anyway.

So I wrote a code like this in AppDelegate.swift:

let settings = FirestoreSettings()
        
settings.isPersistenceEnabled = false
        
COLLECTION_POSTS.firestore.settings = settings
        

But I am met with this error message:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Firestore instance has already been started and its settings can no longer be changed. You can only set settings before calling any other methods on a Firestore instance.'

Is there any way to selectively deny offline persistence for each collection in Firestore?

Upvotes: 3

Views: 546

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

It is unfortunately not possible to control the cache on a per-collection level. Disk based persistence is either on or off, with nothing in between.

You could use two separate instances of the Firestore.firestore() object, as shown in the documentation on accessing multple projects in your application. You'd have two FirebaseOptions/FirebaseApp/Firestore instances for the same project, and enable caching on one and not on the other. But you may get into a pretty tricky situation to keep the documents from the different instances in sync.


On the exception itself:

The exception is pretty clear: you're trying to modify the settings after the client has already been initialized.

You'll need to set firebase.firestore.settings before you first call firestore(). For example, this would be fine:

let settings = FirestoreSettings()
settings.isPersistenceEnabled = false
Firestore.firestore.settings = settings
let COLLECTION_POSTS = Firestore.firestore().collection("posts")
let COLLECTION_USERS = Firestore.firestore().collection("users")     

Upvotes: 1

Related Questions