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.
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:
- The exact, complete path that you want to write to.
- 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 node2.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)

0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.