I am writing a todolist application
there are two screens
MainVC – table
SecondVC – with two testfeeds where the user writes notes
I save when I click on the button
private var databaseRef = Database.database().reference()
ActionButton
let user = Auth.auth().currentUser
self.databaseRef.child((user?.uid)!).child("tasklist").childByAutoId().setValue(["textPrimary":textPrimary, "textSecondary":textSecondary])
I use childByAutoId() because a user can have many notes
Example my database:
GcOialHBMfWxV9AgUJXR4zUsf603 = { // user.uid
tasklist = { // child("tasklist")
"-N9km0vd6W_gs3ljMRyw" = { // .childByAutoId()
textPrimary = 123; //setValue(["textPrimary":textPrimary,
textSecondary = Tasktask; // "textSecondary":textSecondary]
};
"-N9km4EMruNUvSDsCCAY" = { // .childByAutoId()
textPrimary = OtherTask;
textSecondary = Taskkkkk;
};
};
};
How do I get the key of an already created notes?(example -N9km0vd6W_gs3ljMRyw)
I load the data like this
// load data in first VC
let user = Auth.auth().currentUser
var ref = databaseRef.child("(user!.uid)").child("tasklist").childByAutoId()
print(ref)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot.value)
})
}
.childByAutoId() constantly creates a new key (which is not in the database, and I need a key from the database)
Or do I have the wrong approach? Then what should I do?
2
Answers
I am sorry if this answer would better a comment, but I wanted to add a code snippet.
From the firebase documentation:
So as far as I understood, you get the id from the reference (in your example ref) and I could imagine it looks like that:
The
snapshot
object in your last code snippet is of typeDataSnapshot
. In addition to having avalue
, it also has akey
– which is the string generated when you callchildByAutoId
.So:
If you load the entire
tasklist
node, you can loop over thechildren
of the snapshot (whose keys you won’t know) as shown in the Firebase documentation on getting a list of nodes by listening for a value event:To learn more about this, also see: