I have an app where users can create tasks for them to do throughout the day. Similar to a To-do list. I have a node in my firebase database called "Tasks"
under this node is where all the tasks are added.
Here is a visual example:
I am of course able to add data to the firebase database. Here is the code for that:
taskTitle = titleTextField.text!
taskDescription = notesTextView.text
var tasks: [String: Any] = [:] // declaring empty dictionary
tasks["Description"] = taskDescription
tasks["Due Date"] = date_time
database.child("Tasks").child(taskTitle).setValue(tasks)
SO IF THE USER CREATES A NEW TASK, LET'S SAY THER CREATE "TASK 4"
, "TASK 5"
, "TASK 6"
IT WILL LOOK LIKE THIS:
here is the jason data print:
Tasks = {
"Task 1" = {
Description = Abcderf;
"Due Date" = "Nov 17, 2021, 19:11";
};
"Task 2" = {
Description = Abcderf;
"Due Date" = "Nov 17, 2021, 19:11";
};
"Task 3" = {
Description = Abcderf;
"Due Date" = "Nov 17, 2021, 19:11";
};
"Task 4" = {
Description = Notes;
"Due Date" = "";
};
"Task 5" = {
Description = Run;
"Due Date" = "Nov 24, 2021, 12:11";
};
"Task 6" = {
Description = Run;
"Due Date" = "Nov 24, 2021, 12:11";
};
};
}
Here is the code to print this snapshot:
var postRef: DatabaseReference? // declared outside of viewDidLoad()
var refHandle: DatabaseHandle? // declared outside of viewDidLoad()
//set the db ref
postRef = Database.database().reference()
//getting values from db
refHandle = postRef?.observe(DataEventType.value, with: { snapshot in
self.listOftasks.append("")
})
I am just setting a breakpoint at self.listoftasks.append("")
, and then in the console I am doing "po snapshot"
which then prints the JSON object.
What do I need to do, to read only the name of the tasks?
CodePudding user response:
First up, if you only care about the tasks, you should load only the Tasks
node instead of loading the entire database
tasksRef = Database.database().reference("Tasks")
Next up, you'll need to loop over the child nodes in your completion handler:
refHandle = tasksRef?.observe(DataEventType.value, with: { snapshot in
for taskSnapshot in snapshot.children {
print(taskSnapshot.key)
}
})
For this, I recommend also checking out some of the previous questions on looping over child nodes in swift, such as:
Keep in mind: while the above only prints the keys of the tasks, it still retrieves the values of each node too. If you don't need the value in your code, consider keeping a separate node in your database with just the task names (and typically true
values, since a path needs a value to exist) to reduce the bandwidth used.
Finally, having such sequential keys is a common anti-pattern in Firebase, so I recommend reading this classic post: Best Practices: Arrays in Firebase.