【问题标题】:Add data to Firebase instead of SetValue, in Swift 3在 Swift 3 中将数据添加到 Firebase 而不是 SetValue
【发布时间】:2016-10-25 11:40:51
【问题描述】:

我想在当前数据之外添加数据。 我知道的唯一方法是保存当前数据,将其添加到我的应用程序中,然后将其写入 Firebase。但是如果 2 个人在准确的时间做这件事呢?第一个这样做的人 - 将被禁止。

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

【问题讨论】:

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


    【解决方案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")
        }
    

    【讨论】:

    • 如何调用函数?
    猜你喜欢
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2014-08-21
    • 2020-04-11
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多