如何从iOS中的Firebase中的子节点获取数据

时间:2019-03-20 08:30:43

标签: ios swift firebase nosql

我的数据库结构是

appname:
        Tasks:
             childbyautoid1:
                            "name": "myname"
                            "age": "18"
             childbyautoid2:
                            "name": "yourname"
                            "age": "20"

我想知道如何获取所有子节点的名称和年龄的所有数据,因为我不知道childbyautoid

我在写

Database.database().reference().child("Tasks").observe(.childAdded){ (dss) in 
if let value = dss.value  as? [String: AnyObject]{ 

    let name = value["name"] as? String
    let age = value["age"] as? String
    print(name)
    print(age)

}

2 个答案:

答案 0 :(得分:3)

您可以像这样经历每个孩子:

    // Create a reference to the database path
    let ref = Database.database().reference(withPath: "Tasks")

    // You can keep your database synced
    ref.keepSynced(true)

    ref.observe(.value, with: { (snapshot) in

    // Checking if the reference has some values
    if snapshot.childrenCount > 0 {

        // Go through every child
        for data in snapshot.children.allObjects as! [DataSnapshot] {
            if let data = data.value as? [String: Any] {

                // Retrieve the data per child

                // Example
                let name = data["name"] as? String
                let age = data["age"] as? String

                // Print the values for each child or do whatever you want
                print("Name: \(name)\nAge: \(age)")
                }
            }
        }
    })

答案 1 :(得分:0)

尝试使用[[String: Any]]而不是[String: Any],然后为每个Dictionary在其中循环并映射结果,应该是这样的。

if let value = dss.value  as? [[String: Any]]{
    for val in value {
        let name = val["name"] as? String
        let age = val["age"] as? String
        print(name)
        print(age)
    }