Lasse Bickmann
Lasse Bickmann

Reputation: 205

Swift & Firebase - Out of sync after isPersistenceEnabled

I have a problem with my connection between my app and firebase database. After adding:

Database.database().isPersistenceEnabled = true

To my AppDelegate, some of the data is out of sync. To get my data i use:

self.ref?.child("Stores").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let store = Store()
            store.Latitude = dictionary["Latitude"]?.doubleValue
            store.Longitude = dictionary["Longitude"]?.doubleValue
            store.Store = dictionary["Store"] as? String
            store.Status = dictionary["Status"] as? String
            stores.append(store)

            DispatchQueue.main.async {
                self.performSegue(withIdentifier: "LogInToMain", sender: nil)
            }
        }
    })

And on the next ViewController, i use the date to make annotations on a map. Like this:

func createAnnotation(Latitude:Double, Longitude:Double, Store:String, Status:String) {
    let annotation = CustomPointAnnotation()
    let latitude: CLLocationDegrees = Latitude
    let longitude: CLLocationDegrees = Longitude
    annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude)
    annotation.title = Store
    annotation.imageName = "\(Status).png"
    map.addAnnotation(annotation)
}

But the problem is, that the data to the annotation dont change with the database anymore. The app needs to be opened, then closed, then opened again before the data is shown correctly. Can anyone help with that problem?

Upvotes: 3

Views: 1831

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

Since you are using:

Database.database().isPersistenceEnabled = true

then you need to use keepSynced(true) so the data will stay synchronized.

Persistence Behavior:

By enabling persistence, any data that the Firebase Realtime Database client would sync while online persists to disk and is available offline, even when the user or operating system restarts the app. This means your app works as it would online by using the local data stored in the cache. Listener callbacks will continue to fire for local updates.

keepSynced(true):

The Firebase Realtime Database synchronizes and stores a local copy of the data for active listeners. In addition, you can keep specific locations in sync.

for more info check this: https://firebase.google.com/docs/database/ios/offline-capabilities

Upvotes: 3

Related Questions