Looping in Firebase

后端 未结 2 985
野性不改
野性不改 2020-12-20 03:03

I have been trying to find a way to print/isolate each of the children in a part of the JSON data structure in Firebase. I am using swift and another post mentioned and veri

相关标签:
2条回答
  • 2020-12-20 03:28

    Just make an array of snapshot with keys and loop through it just like that if you want keys of "vets":

    let ref = Database.database().reference().child("vets")
    
    ref.observe(.childAdded) { (snapshot) in
        for key in [snapshot.key] {
            print(key)
        }
    }
    

    However, if you want the keys of "vets" children then you can do it like this:

    ref.observe(.childAdded) { (snapshot) in
        guard let snapChildren = snapshot.value as? [String: Any] else { return }
        for (key, value) in snapChildren {
            print(key)
        }
    }
    

    If you need all key-value pairs of "vets" you may get them like this:

    ref.observe(.childAdded) { (snapshot) in
        guard let snapChildren = snapshot.value as? [String: Any] else { return }
        for snap in snapChildren {
            print(snap)
        }
    }
    

    Wanna print value for a certain key of vets children? Let's say you want to print a vet name:

    ref.observe(.childAdded) { (snapshot) in
        guard let snapChildren = snapshot.value as? [String: Any] else { return }
        for (key, value) in snapChildren {
            if key == "Name" {
                print(value)
            }
        }
    }
    

    Note: This code will work assuming your path is Database.database().reference().child("vets") and that each vet entry has some kind of AutoID or UID which is our snapshot.key in the first example.

    0 讨论(0)
  • 2020-12-20 03:50

    Try this:

    FIRDatabase.database().reference().child("vets").observeEventType(.Value, withBlock: { snapshot in
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for child in snapshots {
                    print("Child: ", child)
                }
            }
    
        })
    
    0 讨论(0)
提交回复
热议问题