Search code examples
swiftfirebase-realtime-databaseconnectiondatabase-connection

How to update an array on firebase using the onDisconnectUpdateChildValues


I want to remove the user from an array of users once they disconnect (real time firebase).

For example: John crashed, so remove johns node and reorder the indices. Please check image.

enter image description here

let connectedRef = Database.database().reference(withPath: ".info/connected")
    
    connectedRef.observe(.value, with: { snapshot in
        
        guard let connected = snapshot.value as? Bool, connected else {
            completion(false)
            return
        }
        
        self.database.child("\(groupChatId)_F/users").onDisconnectUpdateChildValues([ ??? ]){ (error, ref) in
            if let error = error {
                print("\(error)")
            }
            completion(true)
        }
    })

I am not entirely sure if it's even possible to do such a thing. If my intuition is true then please provide suggestions on how a problem can be overcome.


Solution

  • First off: arrays like the one you're using here are an anti-pattern in Firebase. I highly recommend reading Best Practices: Arrays in Firebase.

    But aside from that: to update on disconnect you need to specify two things:

    1. The exact, complete path that you want to write to.
    2. The exact value that you want to write to that path.

    Say you want to remove a value/path at users/2 I'd recommend using:

    self.database.child("\(groupChatId)_F/users/2").onDisconnectRemoveValue(){ (error, ref) in
      ...
    

    This does mean that you need to know the path of the user (2 in this example code). If you don't currently know that path, you have two main options:

    • either to remember it in your code when you create the child node. So when you add "Bob", remember in your code that you added him in node 2.

    • or you can make the path idempotent. For example, if you user names are unique, I'd recommend storing them in a structure like this:

      "users": {
        "Alex": true,
        "Bob": true,
        "John": true
      }