Jonas Larsen
Jonas Larsen

Reputation: 378

Writing data to firebase without overwriting it. Swift

I just got my app working on firebase, I just have the small problem of it overwriting the data.

The action:

 @IBAction func Gem(_ sender: UIButton) {
    self.ref.child("users").child(Personnr.text!).setValue(["Fornavn": Fornavn.text!])
    self.ref.child("users").child(Personnr.text!).setValue(["Efternavn": Efternavn.text!])
}

The problem is that it writes the first command, then erases it and writes the second one. Im new to programming, so its probably something simply.

I have clarified text fields from which the user will write the data which will then be uploaded to the database.

@IBOutlet weak var Fornavn: UITextField!

@IBOutlet weak var Efternavn: UITextField!

@IBOutlet weak var Personnr: UITextField!

@IBOutlet weak var Korekort: UITextField!

Any clues on how to avoid the overwrite?

Upvotes: 2

Views: 1831

Answers (3)

Siyavash
Siyavash

Reputation: 980

That is pretty normal so what you can do is make a dictionary like this

let data = ["Fornavn": Fornavn.text!,"Efternavn": Efternavn.text!]

And then do

self.ref.child("users").child(Personnr.text!).setValue(data)

What this does is that it stores both Fornavn and Efternavn data under the Personnr.text Parent node

Upvotes: 2

Tony Nguyen
Tony Nguyen

Reputation: 491

Let's say you have a node with name Personnr.text.

If you want to add more child nodes or update current data on this node, you can use updateChildValues function

Btw, you can optimize your query by:

self.ref.child("users").child(Personnr.text!) .updateChildValues(["Fornavn": Fornavn.text!],["Efternavn": Efternavn.text!])

Upvotes: 1

Yuyutsu
Yuyutsu

Reputation: 2527

Try this

let arrVal = [["Fornavn": Fornavn.text!],["Efternavn": Efternavn.text!]]
self.ref.child("users").child(Personnr.text!).updateChildValues(arrVal)

Reference:https://firebase.google.com/docs/database/ios/read-and-write

Upvotes: 0

Related Questions