ObserveSingleEvent returns old data

I want to get the desired version number of the application when I start the application. But I cannot get the correct key.

I have this code to extract. I am using single event monitoring because I am using this method to check the version number of the required application. This method is only triggered when the application starts checking.

func getVersion(completionHandler: @escaping (Result<Any?>) -> ()) {

     let ref: DatabaseReference! = Database.database().reference().child("version").child("IOS")

     ref?.observeSingleEvent(of: .value , with: { snapshot in

         if snapshot.exists() {    
            let recent = snapshot.value as!  NSDictionary  
            print(recent)
         }
     })
}

      

But does it return the old results? I have isPersistenceEnabled

included in my Appdelegate

.

This is the structure of the database:

enter image description here

I get no results when I use Database.database().reference().child("version").child("IOS").

snapshot.exists false when I use this.

What I had before was: - version | IOS - 1.0

And I get the result when I use Database.database().reference().child("version"), namely {iOS => 1.0}

. I don't understand because this was my old structure.

+3


source to share


2 answers


Firebase Realtime Database syncs and maintains a local copy of the data for active listeners. In addition, you can sync specific locations.

let scoresRef = Database.database().reference(withPath: "scores")
scoresRef.keepSynced(true)

      

The Firebase Realtime Database Client automatically downloads data in these locations and syncs it even if there are no active listeners in the link. You can turn off sync with the following line of code.



scoresRef.keepSynced(false)

      

Haven't tried it but it should work.

+1


source


The method is observeSingleEvent

used for data that doesn't actually change, and as such it will be fetched from the local cache if you have persistence.

This Android solution ( fooobar.com/questions/211734 / ... ) provides a workaround using an alternative method runTransactonBlock

.



Transactions provide the ability to edit any data before saving it. Here we can simply accept the data as correct, since we are only interested in reading the last values.

let ref: DatabaseReference! = Database.database().reference().child("version").child("IOS")
ref.runTransactionBlock({ (data) -> TransactionResult in
    return TransactionResult.success(withValue: data)

}, andCompletionBlock: { (error, success, snapshot) in
    if let snapshot = snapshot, snapshot.exists() {
        if let recent = snapshot.value as? NSDictionary {
            print(recent)
        }
    }
})

      

0


source







All Articles