I have Firebase generating random keys for my entries in a Swift application. How do I find this key if I want to change a specific record? In my example below, I note that the task is completed, but when I click the button, it does not work properly, because I am not referring to a specific task, but to reference the task I need a random generated key.
func doneHit(cell:TaskCell) { if let ip = tableView.indexPathForCell(cell) { var task = tasksInSectionArray[ip.section][ip.row] let tasksRef = ref.childByAppendingPath("tasks") ref.observeSingleEventOfType(.Value, withBlock: { snapshot in let doneRef = tasksRef.childByAppendingPath("\(snapshot.key)/done") if task.done == false { task.done = true cell.checkBox.image = UIImage(named: "checkedbox") doneRef.setValue(task.done) } else { task.done = false cell.checkBox.image = UIImage(named: "uncheckedbox") doneRef.setValue(task.done) } let completedByRef = tasksRef.childByAppendingPath("\(snapshot.key)/completedBy") if task.done == true { completedByRef.setValue(self.user) cell.detailLabel.text = "Completed By: \(self.user)" } else { completedByRef.setValue("") cell.detailLabel.text = "" } }) } }
My Firebase structure:
- tasks
- randomly generated identifier
- randomly generated identifier
Update 1:
I updated my code to get identifiers for all tasks, but the backend update functionality does not work correctly. This allows you to update tasks created in the application. There are 150 tasks that I imported using the web panel. These are the ones I cannot update.
func doneHit(cell:TaskCell) { if let ip = tableView.indexPathForCell(cell) { var task = tasksInSectionArray[ip.section][ip.row] let tasksRef = ref.childByAppendingPath("tasks") var taskID = "" tasksRef.observeSingleEventOfType(.Value, withBlock: { snapshot in for task in snapshot.children { let _tasks = task as! FDataSnapshot let id = _tasks.key print(id) taskID = id } let doneRef = tasksRef.childByAppendingPath("\(taskID)/done") if task.done == false { task.done = true cell.checkBox.image = UIImage(named: "checkedbox") doneRef.setValue(task.done) } else { task.done = false cell.checkBox.image = UIImage(named: "uncheckedbox") doneRef.setValue(task.done) } let completedByRef = tasksRef.childByAppendingPath("\(taskID)/completedBy") if task.done == true { completedByRef.setValue(self.user) cell.detailLabel.text = "Completed By: \(self.user)" } else { completedByRef.setValue("") cell.detailLabel.text = "" } }) } }
source share