I have Firebase generating random keys for my records in a Swift app. How do I go about retrieving that key if I want to change a specific record? In my example below, I\'m mark
Following Tim's answer for Swift 3 and Firebase 4 I had to use the below
for task in snapshot.children {
guard let taskSnapshot = task as? DataSnapshot else {
continue
}
let id = taskSnapshot.key
To create a randomly generated key you need to use childByAutoId()
(which I can't see in your example code).
This will return a Firebase reference you could use and which will return the key with it's .key
property
var post1Ref = ref.childByAutoId()
post1Ref.setValue(post1)
var postId = post1Ref.key
See documentation here
An alternative to Ron's answer involves generating the key first and then using it to set value:
let autoId = databaseReference.childByAutoId().key
databaseReference.child(autoId).setValue(YOUR_VALUE)
tasksRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
for task in snapshot.children {
guard let taskSnapshot = task as? FDataSnapshot else {
continue
}
let id = task.key
// do other things
}
}