我想在Firebase节点中使用锁机制。 我的多人游戏中有这种结构:
-lobby{
- wait room{
- n9Meavvia9XHBjefBfE9kjtID6x2{
- challengeId: "waiting"
- imageURL: "waiting"
- myURLImage: "https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100..."
- player1: "waiting"
}
}
}
在我的逻辑中,搜索游戏的用户应该设置这些参数(例如challengeId
),然后等候室中的用户被等候室移除,并且匹配被建造。如果候诊室里没有用户,最初搜索的用户应该被安排在候诊室。
我的问题是,当更多用户同时为候诊室中的用户搜索时,他们创建两个匹配并且它不正确。我试图使用Firebase事务,但我遇到了同样的问题。对不正确的英语我很抱歉,但我是意大利人。 :)
这是我的交易代码:
let waitNode = self.thisGameRoot.child("wait room")
waitNode.runTransactionBlock({(_ currentData: FIRMutableData) -> FIRTransactionResult in
//self.i += 1
if currentData.hasChildren() {
print("HAS CHILDREN!!!!!!, modifico e setto")
let key = (currentData.children.allObjects[0] as AnyObject).key!!
//key del primo player in sala d'attesa
let newData = self.setAdversaryParameters(adversaryKey: key, waitNode: waitNode, data : currentData)
return FIRTransactionResult.success(withValue: newData)
}
else {
print("NON ho modificato i dati")
// torna un value uguale a quello di partenza, non ha cambiato nulla
return FIRTransactionResult.success(withValue: currentData)
}
}, andCompletionBlock: {(_ error: Error?, _ committed: Bool, _ snapshot: FIRDataSnapshot?) -> Void in
print("transaction n: " ,self.i)
if error != nil {
print("Transaction Error: \(error)")
}
if committed {
print("dati impegnati,in lavorazione(LOCK)")
}
print("Final Value: \(snapshot!.value))")
if self.modified && snapshot!.exists(){
_ = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.segue), userInfo: nil, repeats: false)
}
else{
self.putInWaitRoom(waitNode: waitNode)
}
})
我希望你能帮助我。谢谢!