在这里,我正在聊天应用程序中工作,我想维护接收方的未读计数。我在控制台中的 json 结构看起来像
user_history | |--> user_a_uuid |-> last_msg |-> last_msg_timestamp |-> unread_count
这个问题的范围是,如何增加unread_count
的值。在递增之前,我将 user_a_uuid
和节点 user_history
和 unread_count
作为常量。所以我尝试如下
dbRef.child("user_history")
.child(user_a_uuid)
.child("unread_count")
.runTransactionBlock { (unreadCount) -> TransactionResult in
var value = unreadCount.value as? Int
if value == nil {
value = 0
}
unreadCount.value = value! + 1
return TransactionResult.success(withValue: unreadCount)
}
其实准确地说,这个解决方案是我从here借用的。 。我也尝试遵循 doc 。但问题是,我不想像文档中那样在根节点上运行事务。我只想在 unread_count
文档上运行事务。
我面临的问题:
尝试此代码后,我面临的问题是,unread_count
节点很快被删除,当我在完成 block 内返回 TransactionResult
时,它添加了 未读计数
。问题是由于 unread_count
被删除,该值没有增加。它始终保持为 1
。
提前致谢。
最佳答案
您似乎想要增加存储在节点中的计数器而不影响节点中的其他项目。根据问题中的信息,由于计数存储在代码中,因此在此用例中似乎不需要使用事务 block 。
Prior incrementing i have the user_a_uuid and the node user_history & unread_count as a constant
我相信这意味着您将 unread_count 存储在代码中的变量中,因此如果这是正确的,则只需在代码中递增它并写入节点即可。
从重复的结构开始:
user_history
uid_0
last_msg: "some message"
last_msg_timestamp: "20181028075700"
unread_count: 2
现在我们添加了另一条消息。 var 需要增加,然后 Firebase 中的相应节点需要使用新值进行更新。这是执行此操作的代码:
func updateMsgCount() {
self.unread_count += 1 //this is a class var or however it's stored in code
let unreadCountRef = self.ref.child("user_history").child("uid_0").child("unread_count")
unreadCountRef.setValue(self.unread_count)
但是,假设 unread_count 未存储在代码中,而仅存储在 Firebase 中。以下是读取 unread_count 节点、增加计数并将其存储回 Firebase 的代码。
func updateCount() {
let unreadCountRef = self.ref.child("user_history").child("uid_0").child("unread_count")
unreadCountRef.observeSingleEvent(of: .value, with: { snapshot in
var currentCount = snapshot.value as? Int ?? 0
currentCount += 1
unreadCountRef.setValue(currentCount)
})
}
如果您确实需要一个事务 block ,这里有一个可以完成同样的事情
func updateCountTransactionStyle() {
let unreadCountRef = self.ref.child("user_history").child("uid_0").child("unread_count")
unreadCountRef.runTransactionBlock( { (currentData: MutableData) -> TransactionResult in
var currentCount = currentData.value as? Int ?? 0
currentCount += 1
currentData.value = currentCount
return TransactionResult.success(withValue: currentData)
})
}
关于ios - 如何使用firebase实时数据库ios增加特定节点中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53028308/