在Swift 3中将数据添加到Firebase而不是SetValue

时间:2016-10-25 11:40:51

标签: ios swift firebase firebase-realtime-database swift3

我想添加除当前数据之外的数据。 我知道的唯一方法是保存当前数据,将其添加到我的应用程序中,然后将其写入firebase。但如果2个人在确切的时间内完成该怎么办呢?首先这样做的人将被禁止。

那么您知道将数据添加到Firebase而不是SetValue的其他任何方式吗?

1 个答案:

答案 0 :(得分:1)

要解决此同步值更新问题,请使用 runTransactionBlocks

像这个函数一样,让我们​​说这个引用是noOfPost,而我想做的就是将值增加1

如果两个用户同时增加此参考值,此请求将上传到单独的线程中,并将覆盖数据库中同时更新的可能性: -

func updateTotalNoOfPost(completionBlock : @escaping (() -> Void)){


    let prntRef = FIRDatabase.database().reference().child("_yourNodeRef")

    prntRef.runTransactionBlock({ (returned_Data) -> FIRTransactionResult in
        if let totalPost = returned_Data.value as? Int{
            print(totalPost)
            returned_Data.value = totalPost+1 //Your updated or appended value, or whatever you wanna do with this

            return FIRTransactionResult.success(withValue: returned_Data)
        }else{

            return FIRTransactionResult.success(withValue: returned_Data)

        }
        }, andCompletionBlock: {(error,completion,snap) in

            print(error?.localizedDescription)
            print(completion)
            print(snap)
            if !completion {

                print("The value wasn't able to Update")
            }else{

                completionBlock()
            }
    })

}

调用该函数: -

 updateTotalNoOfPost{
      print("The value was updated")
    }