Eliko Eliko - 1 year ago 96
iOS Question

Add data to Firebase instead of SetValue, in Swift 3

I want to add data in addition to the current data.
The only way I know is save the current data, add it in my app and then write it to the firebase. But what if 2 people do it in the exact time? The one who did it first - will be forbidden.

So do you know any other way to add data to the Firebase instead of SetValue?

Answer Source

To tackle this simultaneous value updation , runTransactionBlocks are used

Like this function, lets say this reference is of noOfPost, and all i want to do is increase the value by 1

If two users increase this reference value simutaneously, This request will be uploaded in the separate Thread, and will override the possibility of simultaneous updates in your Database:-

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{
            returned_Data.value = totalPost+1 //Your updated or appended value, or whatever you wanna do with this

            return FIRTransactionResult.success(withValue: returned_Data)

            return FIRTransactionResult.success(withValue: returned_Data)

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

            if !completion {

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



Calling the function:-

      print("The value was updated")