Tom
Tom

Reputation: 197

Implementation and function of Querying Data Offline - Realtime Database

I'm currently writing data to the realtime database something like this:

function writeData {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        let databaseRef = Database.database().reference().child("users/\(uid)")

        let object = [
            ...
            ] as [String: Any]

        databaseRef.setValue(object)
}

It works fine, but I'm currently trying to reduce the possibility of data loss killing the app. Doing so I've lately browsed the web and found something called: "Querying Data Offline" with the following code:

let scoresRef = Database.database().reference(withPath: "scores")
scoresRef.queryOrderedByValue().queryLimited(toLast: 4).observe(.childAdded) { snapshot in

}

Am I right assuming that with the example above, the last 4 data write attempts are being saved until there's a connection again - as soon as there is, they'll be uploaded?

If that's the function suiting my desires - how to implement it? How to connect it with my writeData() function? To what does "scores" in the example above refer to?

Upvotes: 0

Views: 35

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

If the Firebase client is not connected to its servers, any write operations from that app are always queued by the Firebase client. When the connection is restored, the Firebase client sends the queued writes to the server.

When you enable disk persistence the Firebase client writes the queued write operations to a file on disk. The Firebase client also writes any results from recent read operations to that same file. That way they will also survive any app shutdown, and will be available/retried when the user (re)starts the app and has a connection.

The code you showed has nothing to do with the queued writes in any way. This:

scoresRef.queryOrderedByValue().queryLimited(toLast: 4).observe(.childAdded) { snapshot in

Attaches a listener/observer to scoresRef to get the 4 highest scores. If the client is connected to the server, this will be the most recent/highest scores. If the client is not connected to the server, but has data for scoresRef on disk, it will be the most recent/highest scores as the client last saw them.

Upvotes: 1

Related Questions