简体   繁体   中英

How can I retrieve nested firebase data in my ios app?

I have nested database in firebase. I have to read data from firebase to my application but in this point data little bit complicated so I can't retrieve correctly. I have to take "adres", "isim", "tarih" and "urunler" node also I can take adres data with childSnapshot and for loop but I lose order.Can you help me is there any way to retrieve this kind of data with order? Here my database json:

"orders" : {
"kullanicilar" : {
  "D5wmYp3YyegUOwtpVeqa0IoKnqA2" : {
    "-Lu3Fl2QnSFa5vhrKOzv" : {
      "Tshirt" : 4,
      "adres" : {
        "siparis alinma adresi" : "Bostancı - Yan Yol - Yan apt no:4 - Kadıköy - 7 - 23 - 29.103910631539957 - 40.96400403065958",
        "siparis edilme adresi" : "Bostancı - Yan Yol - Yan apt no:4 - Kadıköy - 7 - 23 - 29.103910631539957 - 40.96400403065958"
      },
      "isim" : {
        "username" : "Testçi"
      },
      "tarih" : {
        "teslim alinma tarihi" : {
          "alinma saati" : "10:00 - 11:00",
          "alinma tarihi" : "19/11/2019"
        },
        "teslim edilme tarihi" : {
          "alinma tarihi" : "21/11/2019",
          "teslim saati" : "18:00 - 19:00"
        }
      },
      "toplam tutar" : {
        "toplam paket tutari" : 55.6
      },
      "urun adetleri" : {
        "adetler" : [ 4 ]
      },
      "urunler" : {
        "Tshirt" : 4
      }
    },
    "-Lu3G-97OfWJB1u34gJ8" : {
      "Sweatshirt" : 3,
      "Tshirt" : 4,
      "adres" : {
        "siparis alinma adresi" : "Bostancı - Yan Yol - Yan apt no:4 - Kadıköy - 7 - 23 - 29.103910631539957 - 40.96400403065958",
        "siparis edilme adresi" : "Bostancı - Yan Yol - Yan apt no:4 - Kadıköy - 7 - 23 - 29.103910631539957 - 40.96400403065958"
      },
      "isim" : {
        "username" : "Testçi"
      },
      "tarih" : {
        "teslim alinma tarihi" : {
          "alinma saati" : "18:00 - 19:00",
          "alinma tarihi" : "22/11/2019"
        },
        "teslim edilme tarihi" : {
          "alinma tarihi" : "27/11/2019",
          "teslim saati" : ""
        }
      },
      "toplam tutar" : {
        "toplam paket tutari" : 99.1
      },
      "urun adetleri" : {
        "adetler" : [ 4, 3 ]
      },
      "urunler" : {
        "Sweatshirt" : 3,
        "Tshirt" : 4
      }
    }
  },

And here I tried to get data from firebase I take these data to arrays. And here my code which tried for retrieve:

func firebaseConnection() {
    ref = Database.database().reference()
    ref?.child("orders").child("kullanicilar").observe(.childAdded, with: { (datasnapshot) in

        let imageD = datasnapshot
        self.userId = imageD.key

        self.ref?.child("orders").child("kullanicilar").child(self.userId).observe(.childAdded, with: { (snapshot) in


            // ADRESLERI TUTAN KOD BURASIDIR.. ADRESLERI ALIR VE HEM ARRAY HEM DE SOZLUGE KAYIT EDER..
            let adresChild = snapshot.childSnapshot(forPath: "adres")
            for adr in adresChild.children {
                let adresSnap = adr as! DataSnapshot
                self.adresValuesArray.append(adresSnap.value! as! String)

            }

            let tarihChild = snapshot.childSnapshot(forPath: "tarih").childSnapshot(forPath: "teslim alinma tarihi")
            for trh in tarihChild.children {
                let tarihSnap = trh as! DataSnapshot
                self.tarihValuesArray.append(tarihSnap.value! as! String)
            }

            let tarihChildteslim = snapshot.childSnapshot(forPath: "tarih").childSnapshot(forPath: "teslim edilme tarihi")
            for trhts in tarihChildteslim.children {
                let tarihTeslimSnap = trhts as! DataSnapshot
                self.tarihTeslimValuesArray.append(tarihTeslimSnap.value! as! String)

            }


            let urunlerChild = snapshot.childSnapshot(forPath: "urunler")

            for urn in urunlerChild.children {
                let urunSnap = urn as! DataSnapshot
                //self.urunlerArray.updateValue(urunSnap.value! as! Int, forKey: urunSnap.key as! String)

                self.urunlerArray.append(urunSnap)
                print(self.urunlerArray)



            }


            })
        })

}

I don't know what those node names mean - perhaps Turkish so I am using an English version which is similar.

Here's structure like yours

orders
   all_users
      uid_0
         TShirt: 4
         addresses:
            address_0: ""
            address_1: ""
         delivery_dates
            delivery_0
              delivery_date: "19/11/2019"
              delivery_time: "10:00 - 11:00"
            delivery_1
              delivery_date: "21/11/2019"
              delivery_time: "18:00 - 19:00"
         name
            username: "some username"

we are using.childAdded to read in each uid node within all_users - that will iterate over them one at a time giving access to the child data returned in the snapshot.

Here's the code to read each user node and print out all of the data.

func readUserDeliveryInfo() {
    let ordersRef = self.ref.child("orders")
    let allUsersRef = ordersRef.child("all_users")
    allUsersRef.observe(.childAdded, with: { snapshot in
        let userId = snapshot.key
        print("data for user: \(userId)")

        let tshirt = snapshot.childSnapshot(forPath: "TShirt").value as? Int ?? 0
        print("t-shirt: \(tshirt)")

        let allAddresses = snapshot.childSnapshot(forPath: "addresses")
        let addressArray = allAddresses.children.allObjects as! [DataSnapshot]
        for addressSnap in addressArray {
            let addressKey = addressSnap.key
            let address = addressSnap.value as! String
            print("address: \(addressKey)  \(address)")
        }

        let allDeliveries = snapshot.childSnapshot(forPath: "delivery_dates")
        for delivery in allDeliveries.children.allObjects as! [DataSnapshot] {
            let deliveryId = delivery.key
            let deliveryDate = delivery.childSnapshot(forPath: "delivery_date").value as? String ?? "No date"
            let deliveryTime = delivery.childSnapshot(forPath: "delivery_time").value as? String ?? "No Time"
            print(deliveryId, deliveryDate, deliveryTime)
        }

        let nameSnap = snapshot.childSnapshot(forPath: "name")
        let userName = nameSnap.childSnapshot(forPath: "username").value as? String ?? "No username"
        print("username: \(userName)")
    })
}

and the output

data for user: uid_0
t-shirt: 4
address: address_0  some address 0
address: address_1  some address 1
delivery_0 19/11/2019 10:00 - 11:00
delivery_1 21/11/2019 18:00 - 19:00
username: some username

A few things to note:

Firebase DataSnapshot are very powerful so leverage them as long as you can - they will keep data ordered and give easy access to child data.

let tshirt = snapshot.childSnapshot(forPath: "TShirt")

When I do need to iterate over the data in the snapshot, I cast it to an array (which keeps the order unlike a Dictionary) and I cast the child data as DataSnapshots themselves.

let addressArray = allAddresses.children.allObjects as! [DataSnapshot]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM