Reputation: 1137
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?
Upvotes: 0
Views: 739
Reputation: 9945
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{
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()
}
})
}
Calling the function:-
updateTotalNoOfPost{
print("The value was updated")
}
Upvotes: 1