Swift Firebase访问子快照数据

时间:2016-09-21 18:00:32

标签: ios swift firebase firebase-realtime-database

我目前正在尝试从Swift中的子快照访问数据。这是我的代码(在Swift 3 / Firebase更新之前有效):

 if let achievements = snapshot1.childSnapshotForPath("Achievements").children.allObjects as? [FIRDataSnapshot] {


                    if achievements.count != 0 {

                        if let val = achievements[0].value!["somevalue"] as? Int {
                            self.dict["somevalue"] = val
                        }


                    }

所以我在这里要做的是创建子快照的变量(成就),并从中访问子快照数据。成就[0]将只返回第一个值。但是,这似乎不起作用。我该怎么做呢?

我目前正在快照中进行此操作(' observeType:.ChildAdded')

我的Firebase数据库看起来像这样:

Achievements{

randomId1 {
somevalue : somevalue
}

randomId2 {
somevalue2 : somevalue2
}
}

更新的代码:

 func loadData() {

        ref.child("Players").observe(FIRDataEventType.childAdded) { (snapshot:FIRDataSnapshot) in

            if let value = snapshot.value as? [String:AnyObject], let username = value["Username"] as? String {

            }

            if let value = snapshot.value as? [String:AnyObject], let ranking = value["Rank"] as? String {

            }

            if let childSnapshot = snapshot.childSnapshot(forPath: "Achievements").children.allObjects as? [FIRDataSnapshot] {

                if childSnapshot.count != 0 {

                    if let achievement1 = childSnapshot[0].value!["Rookie"] as? String {
                        print(achievement1)
                    }

                }
            }

        }

    }

JSON树:

Players {

PlayerID {

Username

Rank

Achievements {

Rookie: yes

}


}

1 个答案:

答案 0 :(得分:4)

尝试: -

 if let childSnapshot = snapshot.childSnapshot(forPath: "Achievements") as? FIRDataSnapshot{

                if let achievementDictionary = childSnapshot.value as? [String:AnyObject] , achievementDictionary.count > 0{

                    if let achieveMedal = achievementDictionary["Rookie"] as? String {

                        print(achieveMedal)

             }        
       }
    }