PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 20, 2022

[FIXED] How to update an array on firebase using the onDisconnectUpdateChildValues

 April 20, 2022     connection, database-connection, firebase-realtime-database, swift     No comments   

Issue

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
    }
    


Answered By - Frank van Puffelen
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing