-2

In my app is tableview where i want to show all child of my customers. This is database structure:

enter image description here

When previously under Customers I had only one child then I knew how to show customers when path was usersDatabase/userID/Customers. But in this moment my path is usersDatabase/userID/Customers/userSpecificName and my tableview show blank cell. What I must add in my code to properly working of code?

This is code when I import data from Database:

let userID = Auth.auth().currentUser!.uid
    ref = Database.database().reference().child("usersDatabase").child(userID).child("Customers")

    ref.observe(DataEventType.value, with: { (snapshot) in
        if snapshot.childrenCount > 0 {
            self.services.removeAll()
            self.filteredServices.removeAll()
            for results in snapshot.children.allObjects as! [DataSnapshot] {
                let results = results.value as? [String: AnyObject]
                let name = results?["Name and surname"]
                let phone = results?["Phone"]
                let customerID = results?["ID"]

                let myCustomer = CustomerModel(name: name as? String, phone: phone as? String, customerID: customerID as? String)
                self.services.append(myCustomer)
                self.filteredServices.append(myCustomer)
            }
            self.tableView.reloadData()
        }
    })

What I should add to line ref = Database.database().reference().child("usersDatabase").child(userID).child("Customers") that tableview show child of added Customers (Ben Smith and Tom Cruise)?

Khushbu
  • 2,342
  • 15
  • 18
  • i dont understand, Havnt you already queried `ref = Database.database().reference().child("usersDatabase").child(userID).child("Customers")` and displayed it? – Cerlin May 17 '18 at 06:40
  • @CerlinBoss My current code with above database structure show nothing. Previously i have database: userDatabase/userID/Customers/ and contain 2 child with autoID - my tableview cell show value of this two child. But now I have path when i add child with custom ID (Ben Smith and Tom Cruise) : userDatabase/userID/Customers/childWithCustomID/ and I want to show in cell their child's value but with above code cell shows nothing... – Christopher Lowiec May 17 '18 at 06:52
  • maybe in let results = results.value as? [String: AnyObject] is the problem cause you don't have Value in this path you have to loop every child and fetch the data from the first index. checkout if myCustomer is nil ? – Osman May 17 '18 at 07:43
  • @Osman myCustomer is nill because call path userDatabase/userID/Customers has non value child. That's my problem - how to get access to value in last child with custom ID (Ben Smith and Tom Cruise) – Christopher Lowiec May 17 '18 at 08:09

1 Answers1

0

This answer is similar to a prior answer here

What you want to do is to treat each child in Customers as a DataSnapshot, then the children can be accessed.

Given a Firebase structure:

usersDatabase
  uid_0
     Customers
        Ben Smith
           data: "Some data"
        Tom Cruise
           data: "Some data"
  uid_1
     Customers
        Leroy Jenkins
           data: "Some data"
  uid_2
     Customers
        De Kelly
           data: "Some data"
     etc

The code to print out each user and their customers is

let usersDatabaseRef = Database.database().reference().child("usersDatabase")
usersDatabaseRef.observe(.value, with: { snapshot in
    print("there are \(snapshot.childrenCount) users")
    for child in snapshot.children {
        let childSnap = child as! DataSnapshot
        print("user: \(childSnap.key)")
        let userCustomerSnap = childSnap.childSnapshot(forPath: "Customers")
        for customer in userCustomerSnap.children {
            let customerSnap = customer as! DataSnapshot
            print(" customer: \(customerSnap.key)")
        }
    }
})

and the output

there are 3 users
user: uid_0
 customer: Ben Smith
 customer: Tom Cruise
user: uid_1
 customer: Leroy Jenkins
user: uid_2
 customer: De Kelly
 customer: Leonard Nimoy
 customer: William Shatner

Edit: the OP wanted to know how to get to the data node under each customer so here's a slightly modified version with output

let usersDatabaseRef = Database.database().reference().child("usersDatabase")
usersDatabaseRef.observe(.value, with: { snapshot in
    print("there are \(snapshot.childrenCount) users")
    for child in snapshot.children {
        let childSnap = child as! DataSnapshot
        print("user: \(childSnap.key)")
        let userCustomerSnap = childSnap.childSnapshot(forPath: "Customers")
        for customer in userCustomerSnap.children {
            let customerSnap = customer as! DataSnapshot
            let dict = customerSnap.value as! [String: Any]
            let value = dict["data"] as! String

            print(" customer: \(customerSnap.key)")
            print("    and their data is: \(value)")
        }
    }
})

and the output

there are 3 users
user: uid_0
 customer: Ben Smith
    and their data is: some data
 customer: Tom Cruise
    and their data is: some data
user: uid_1
 customer: Leroy Jenkins
    and their data is: some data
user: uid_2
 customer: De Kelly
    and their data is: some data
 customer: Leonard Nimoy
    and their data is: some data
 customer: William Shatner
    and their data is: some data
Jay
  • 34,438
  • 18
  • 52
  • 81
  • Ok, that's simple. But when I want to print in tableview cell value of user's customers? For example: current user is uid_0 and print in table view first cell "Some data" and in second cell "Some data"? – Christopher Lowiec May 18 '18 at 14:42
  • @KrzysztofŁowiec In my answer, the customerSnap is a DataSnapshot which is a key: value pair; the key is the customer name *Ben Smith* for example and the value is another key: value pair of *data: 'Some Data'*. So casting it to a dictionary is one option; *let dict = customerSnap.value as! [String: Any]* and then *let value = dict["data"] as! String* – Jay May 18 '18 at 17:02
  • @KrzysztofŁowiec It you take a look at my answer, I included the Firebase structure I used, the tested code and finally the specific output from that code. If it's not working for you, I would suspect your Firebase structure does not match mine. Also note that I don't have any error checking in my code (guard statements for example) so if the structure is not exact, it could crash the app. – Jay May 18 '18 at 20:08
  • unfortunately your above code without added line form last comment print this: there are 1 users user: 7Uut9I0etYTVYWCS6aOIgDaBbBF3 customer: Ben Smith customer: Sasha Bell customer: Tom Cruise - when I add lines of code from your last comment console print this: there are 1 users user: 7Uut9I0etYTVYWCS6aOIgDaBbBF3 customer: Ben Smith - what's wrong? – Christopher Lowiec May 18 '18 at 20:09
  • @KrzysztofŁowiec That code is copy and pasted directly from a working project as well as a copy and paste from the console output. I would suggest looking at your structure as it will be different than mine. To test, I just now copied the code in my answer and pasted it back into a new project and the output is identical. – Jay May 18 '18 at 20:13
  • you have in your's database structure Customers/Ben Smith and value but I have before value child id. Maybe this is problem? – Christopher Lowiec May 18 '18 at 20:13
  • @KrzysztofŁowiec I just added some additional code to demonstrate how to get to each *data* node under each customer, and included the output as well. I also additional customers to my Firebase structure so you can see how it's put together. And yes, your structure has a child id under each customer wheras I have a key: value pair, which means your Firebase is slightly different and will have to add additional code to read within that node - fortunately it's easy as the pattern repeats; treat it as a DataSnapshot, and get it's child value. – Jay May 18 '18 at 20:22
  • @KrzysztofŁowiec Please don't post code in comments as it's a bear to try to read. If you have an additional question, post it, let us know what you've tried and what's not working and we'll take a look! – Jay May 22 '18 at 17:44
  • This is link to my question - can you look? https://stackoverflow.com/questions/50473801/update-childs-value – Christopher Lowiec May 22 '18 at 17:56