askaale askaale - 2 months ago 9
Swift Question

Swift Firebase access data inside child snapshot (by childAdded)

I posted a question previously regarding how to access data inside a child snapshot, where I got a very well-working answer. However, this solution only allowed me to retrieve the data by value - and not my child. You see, I had a JSON tree-structure like this:

Players {

PlayerID {

Username

Rank

Achievements {

Rookie: yes

}


}


And then I realized that I really need multiple 'childByAutoId' under the 'Achievements' - that will look something like this:

Player {

PlayerID {

Username

Rank

Achievements {

autoID1 {

isAchieved: yes

}

autoID2 {

isAchieved: yes

}

}

}


So how would I go on trying to grab the very ChildValues of each childByAutoId? I know for a fact that this works with the 'ChildAdded' on observe Snapshot, however - this doesn't seem to be a feature here.

Here is the code I have right now:

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)

}
}
}


Help would be greatly appreciated!

Answer

How about a JSON tree structure like this:-

Achievements : {

 achievement1 : true,
 achievement2 : true,
 achievement3 : false,
 achievement4 : true,

}

For retrieving your achievements:-

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

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

               for each in achievementDictionary{
                  print(each.0) // achievement name
                  print(each.1)  // isAchieved (true/false)
               }

         }        
   }
}

It's not advisable to add such deep nodes in your DB for navigation reason's .

But this code will also work for the childByAutoID case, i.e each.0 will be your autoID AND each.1 will become that id's corresponding dictionary.For deeper details of that dictionary just navigate through the dictionary