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

Wednesday, April 20, 2022

[FIXED] How to both read and write when using onDisconnectUpdateChildValues - firebase swift

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

Issue

I am trying to decrement observerCount when a user disconnects. How do you do it?

My code:

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)_A").onDisconnectUpdateChildValues(["observersCount": 0]){ (error, ref) in
            if let error = error {
                print("\(error)")
            }
            completion(true)
        }

        
    })

Solution

There is no way to read from the database in an onDisconnect handler. Essentially, the operation has to be a pure set, where the data you write is known when you attach the handler.

Luckily for this use-case, Firebase added an atomic increment() operation a while ago, which is perfect here. I haven't used it in Swift myself, but it should be something like:

.onDisconnectUpdateChildValues([
  "observersCount": firebase.database.ServerValue.increment(-1)
])


Answered By - Frank van Puffelen
Answer Checked By - Candace Johnson (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