简体   繁体   中英

What would be the most efficient way to check equality of a Firebase live database node value and also change it?

在此处输入图片说明

Above is what I have in my live database in Firebase. What I am trying to do is check if the current user's partyStatus is equal to the bool of false or true. And if it is false I want to change it to true.

This is what I tried so far:

usersReference.observeSingleEvent(of: .value, with: { (snapshot) in
  if snapshot.hasChild(uid) { 
    //continue another observeSingleEvent for the next value which is "partyStatus" then check the value then change it 
  } 

How can I do this more efficiently with Firebase and Swift?

You current code load the entire usersReference to then check if a single child exists in it.

A more efficient way to do the same check is to only load the reference for that user and then check if the snapshot exists:

usersReference.child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
  if snapshot.exists() { 
    if snapshot.childSnapshot(forPath: "partyStatus") as! Bool == false {
      usersReference.child(uid).child("partyStatus").setValue(true)
    }
  } 

Here's some sample code that could be used.

What we are doing here is examining the specific node in question for user_0, the partyStatus node. If it exists, get it's current value (assuming it's a bool) then toggle it (false to true or true to false) and if it doesn't exist, create it with a default value of false.

let ref = self.ref.child("users").child("user_0").child("partyStatus")
ref.observeSingleEvent(of: .value, with: { snapshot in
    if snapshot.exists() {
        let isPartying = snapshot.value as! Bool
        ref.setValue(!isPartying)
    } else {
        ref.setValue(false) //it doesn't exist to set to default of false
    }
})
//note that self.ref is a class var ref to my Firebase.

Did you try runTransactionBlock , Simply take the value , test , and return new value :

usersReference.child(uid).child("partyStatus").runTransactionBlock { (data) -> TransactionResult in
        let result = data
        // data = partyStatus value 

        if var value = data.value as? Bool {
           if value == false { // if value is false will change value to true in database
              value = true
              result.value = value 
           } // if not that mean the value is true and will return true
        }

        return TransactionResult.success(withValue: result)
    }

And for more information about runTransaction Firebase Doc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM