Swift: How to fix infinite loop when adding a value to a Firebase variable

后端 未结 2 597
情话喂你
情话喂你 2021-01-16 12:13

I have this piece of code in my program that should allow a user to tap on a message and the score should increase by one:

super.collectionView(collectionVie         


        
2条回答
  •  借酒劲吻你
    2021-01-16 12:53

    Ivan's answer will solve the current problem you have. But loading all messages from the server to detect which one the user clicked sounds like a potentially big waste of bandwidth.

    If you're showing a list of messages from Firebase to the user, I recommend keeping track of the key of each message. With that information, you won't have scan all messages, but can instead directly look up the message that was clicked and increase its score with a transaction:

    rootRef.child("messages").child(postID).child("score").runTransactionBlock({ (currentData: FIRMutableData) -> FIRTransactionResult in
      // Set value and report transaction success
      currentData.value = currentData.value + 1
      return FIRTransactionResult.successWithValue(currentData)
    }) { (error, committed, snapshot) in
      if let error = error {
        print(error.localizedDescription)
      }
    }
    

    A transaction will also solve the potential race condition you now have: if two users click the same message at almost the same time, one might be overwriting the score-increment of the other.

提交回复
热议问题