Home > Mobile >  Read and write data Firebase
Read and write data Firebase

Time:08-19

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?

CodePudding user response:

The snapshot object in your last code snippet is of type DataSnapshot. In addition to having a value, it also has a key - which is the string generated when you call childByAutoId.

So:

ref.observeSingleEvent(of: .value, with: { (snapshot) in
    print(snapshot.key) //            
  • Related