askaale askaale - 2 months ago 98
Swift Question

Swift Firebase Access child snapshot data

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

}


}

Answer

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)

             }        
       }
    }
Comments