首页 > 解决方案 > 如何在 swift4 中设置 firebase 事务

问题描述

在我的应用程序中,有一个按钮可以打开和关闭,但是当从多个用户单击它时,像“真假真假假假”这样的错误发生,它必须按顺序排列,但由于同时输入,像假 3 次,为此我编写了代码,但它不起作用

func stateTransaction() {

let ref = Database.database().reference().child("Button")

        ref.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in

            ref.queryLimited(toLast: 1).observeSingleEvent(of: .childAdded) { (snapshot) in

                let state = snapshot.value as! Bool

                if state == false {

                    ref.childByAutoId().setValue(true)
                    ref.queryLimited(toLast: 1).observeSingleEvent(of: .childAdded, with: { (snapshot) in
                        print(snapshot.value as! Bool)
                        currentData.value = state
                    })

                } else {

                    ref.childByAutoId().setValue(false)
                    ref.queryLimited(toLast: 1).observeSingleEvent(of: .childAdded, with: { (snapshot) in
                        print(snapshot.value as! Bool)
                        currentData.value = state
                    })
                }

                }

                return TransactionResult.success(withValue: currentData)

        }) { (error, committed, snapshot) in
            if let error = error {
                print(error.localizedDescription)
            }
        }

}

这是我的代码,我的代码有什么问题,我该如何解决?提前感谢您。

标签: swiftfirebasefirebase-realtime-databasetransactions

解决方案


推荐阅读