Chris
Chris

Reputation: 437

Swift 4, Firebase how to observe the snapshot and convert into object

My Firebase datastructure looks like this: enter image description here

user is the parent, underneath it is the user uid and Dream, Grocery list is the note titles and they have their content. I am trying to observe the value of the titles and put them into an array to put in a tableview. This is what I have so far but since the titles of the note are different every time, I dont know how to do a model for that:

 DataService.ds.REF_CURRENT_USER.observe(.value) { (snapshot) in
        for snap in snapshot.children.allObjects as! [DataSnapshot] {
            print("Note Title:\(snap.key)")
        }
    }

This prints out everything including email and provider but I dont want that I just want it to print Dream and Grocery List

Upvotes: 0

Views: 1143

Answers (1)

Yogesh Tandel
Yogesh Tandel

Reputation: 1754

Use the below code to get your required values

    guard let uid = Auth.auth().currentUser?.uid else {
        return
    }

    let ref = Database.database().reference().child("users").child("\(uid)")
    ref.child("Dream").observe(.value, with: { (snapshot) in
        guard let dictionary = snapshot.value as? [String : AnyObject] else {
            return
        }
        print(dictionary["content"] as? String)

    }, withCancel: nil)

    ref.child("Grocerylist").observe(.value, with: { (snapshot) in
        guard let dictionary = snapshot.value as? [String : AnyObject] else {
            return
        }
        print(dictionary["content"] as? String)

    }, withCancel: nil)

Upvotes: 1

Related Questions