在此应用程序中,每个用户都有一个“投票”计数器,但它仅在同一用户投票时才有效,当另一个用户尝试在该引用中执行 FIRTransaction 时,它返回 nil。规则设置为任何用户。
当我需要 user2 更新 user1 的“投票”值时,它不会读取该键值来执行事务 block ,因此它返回 nil。
votesCountRef = ref.child("user1").child("votes")
votesCountRef.runTransactionBlock( { (currentData) -> FIRTransactionResult in
let value = currentData.value! as! Int
currentData.value = value + 1
return FIRTransactionResult.successWithValue(currentData)
})
结果:
Received votes actual value: Optional() Could not cast value of type 'NSNull' (0x110684600) to 'NSNumber' (0x10fce92a0).
但是当原始用户运行它时,它会成功运行。
user1 的 Json 树:
{
"userUID" : "user1",
"votes" : 2
}
数据库规则:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
感谢@Frank,我可以这样管理它:
ownerReceivedVotesCountRef.runTransactionBlock( { (currentData) -> FIRTransactionResult in
let value = currentData.value as? Int ?? 0
currentData.value! = (value as Int) + 1
return FIRTransactionResult.successWithValue(currentData)
})
最佳答案
事务处理程序最初以客户端对当前值的最佳猜测运行。通常这将是 nil
,因此您的代码必须处理它。
Note: Because
runTransactionBlock:andCompletionBlock:
is called multiple times, it must be able to handlenil
data. Even if there is existing data in your remote database, it may not be locally cached when the transaction function is run, resulting innil
for the initial value.
这样的事情应该适用于您的情况:
let value = currentData.value as? Int ?? 0
关于swift - Firebase 3 无法修改其他用户创建的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37686308/