I have added some data to the Firebase Realtime Database. It's in two parts, users and bookings. My problem is that when a user books a ride it gives a different uid, I would like it to be when a user books a ride it is under the same uid. Also, if the switch is on I would like to put it under the same child node, booking, but it comes into different nodes when saving. Any help would be highly appreciated.
func Save(){
let key = ref.childByAutoId().key
let Booking = [
"id": key as Any,
"What Date": atALaterDate.text! as String,
"What Time": hoursMinutesTextField.text! as String,
"To What Time": ToWhatTime.text! as String,
"Requests or Notes": SRtextfield.text! as String
]
as [String : Any]
ref.child(key!).setValue(Booking)
}
this is where I would like it to be under one node, in conjunction with the one above it.
func Save2(){
let key = ref.childByAutoId().key
if Switch.isOn{
let passengers = [
"Passengers": Stepperlabel.text! as String,
"passenger Age 1": AgeOfChild1.text! as String,
"passenger Age 2": AgeOfChild2.text! as String,
"passenger Age 3": AgeOfChild3.text! as String,
"passenger Age 4": AgeOfChild4.text! as String,
"passenger Age 5": AgeOfChild5.text! as String,
"passenger Age 6": AgeOfChild6.text! as String,
]
as [String : Any]
ref.child(key!).setValue("booking")
}else{
print("Hello")
return
}
}
CodePudding user response:
I believe the question is how to add additional data to a node.
The important bit is to keep a reference to the node you want to write to and use it with update
to add/change existing data. If update
is used on a node that doesn't exist, it will be added.
So here's an example. Suppose we have a chatting app and we want to write an initial String of Hello, World, and then add an additional string of What's up? to that same node
let messagesRef = self.ref.child("messages") //the top level node
let thisMsgRef = ref.childByAutoId() //create a child node
thisMsgRef.setValue( ["msg": "Hello, World"]) //create the node, write data
thisMsgRef.updateChildValues(["anotherMsg": "Whats up?"]) //add addl data
this results in the following structure
messages
-Jy444f476u6...
anotherMsg: "Whats up?"
msg: "Hello, World"
If you want to re-use the node over and over, a reference to it could be stored as class var and then anytime you want to write to it, just reference the var...
class ViewController: NSViewController {
var myMsgRef: DatabaseReference!
then somewhere later in code
func writeInitialData() {
let ref = self.ref.child("messages")
self.myMsgRef = ref.childByAutoId()
self.myMsgRef.setValue( ["msg": "Hello World"])
and then when you want to add additional data
func addAdditonalData() {
self.myMsgRef.updateChildValues(["anotherMsg": "Whats up?"])