How to store a Firebase ListenerRegistration object in UserDefaults?

122 Views Asked by At

I'm writing a wrapper for storing, retrieving, and removing a snapshot listener from UserDefaults. I'm having a few issues however. I'm attempting to store it by doing the following:

  1. Encode the ListenerRegistration listener into Data
  2. Update my activeListeners dictionary ([String:Data]) property with the new key + data
  3. Store the updated activeListeners dictionary in UserDefaults
func storeListener(listener: ListenerRegistration, for objectId: String, atPath path: AppAPI.Path) {
        let key = formatKeyForListener(objectId: objectId, path: path)
        do {
            let encodedListenerData = try NSKeyedArchiver.archivedData(withRootObject: listener, requiringSecureCoding: false)
            activeListeners.updateValue(encodedListenerData, forKey: key)
            UserDefaults.standard.set(activeListeners, forKey: Strings.listenersKey)
            UserDefaults.standard.synchronize()
        } catch {
            print("Error encoding listener with key: \(key)\nError: \(error.localizedDescription).")
        }
    }

Unfortunately, I'm seeing the following error: Error: The data couldn’t be written because it isn’t in the correct format...

1

There are 1 best solutions below

0
Doug Stevenson On

Firestore listeners do not persist between app launches. When the app process is killed by any means, all of the listeners are gone and do not come back when the app launches again. If you want the listeners to come back at next launch, you will need to write code to establish those listeners again, and decide what to do with any documents they produce. If that's what you want, then you should focus your efforts on figuring out how to represent those listeners in your storage system (maybe just a collection or document path will do), and reconstitute them at the time of launch.