3
votes

I am currently trying to access data from a child snapshot in Swift. Here is my code that I have (which worked before the Swift 3/Firebase update):

 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
                        }


                    }

So what I am trying to do here, is to create a variable of a child snapshot (achievements), and access child snapshot data from it. The achievements[0] will simply return the very first value. However, this doesn't seem to work. How should I approach this?

I am currently doing this inside a snapshot already (of 'observeType:.ChildAdded')

My Firebase DB looks like this:

Achievements{

randomId1 {
somevalue : somevalue
}

randomId2 {
somevalue2 : somevalue2
}
}

Updated code:

 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 Tree:

Players {

PlayerID {

Username

Rank

Achievements {

Rookie: yes

}


}
1
Give your full function. And your Actual JSON tree, its hard to decipher from what you gave. - Dravidian
I have now provided you with the full code and JSON tree. I really can't seem to find a way to grab the childsnapshot data, the code above returns an error. I have also tried to define it as [String:AnyObject] - but this only results in a nil. - askaale
And to be clear, I simply just want to return the 'yes' from the 'Rookie'-value. - askaale

1 Answers

5
votes

Try :-

 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)

             }        
       }
    }