Reputation: 406
Disclaimer: I am very new to coding and Firebase.
My JSON tree looks like this :
“MAIN LEAGUE“ : {
“Team Alpha“ : {
"Team Score" : “50”,
"Total Time " : "02:22:05",
"Team Name" : “Team Alpha“,
},
“Team Bravo“ : {
"Team Score" : “200”,
"Total Time" : "02:09:58",
"Team Name" : “Team Bravo“
},
“Team Charlie“ : {
“Team Score“ : “150”,
"Total Time" : "02:16:50",
"Team Name" : “Team Charlie“
}
}
I am trying to query the database and present a new tableview whereby the teams are ranked by highest "Team Score".
So trying to show, in this order :
" Team Bravo" : "200"
" Team Charlie" : "150"
" Team Alpha" : "50"
I'm a bit lost. I have tried, to no avail (the below returns nothing in the tableview):
struct content {
var sTitle : String!
var sValue : Any!
init(sTitle: String, sValue: Any) {
self.sTitle = sTitle
self.sValue = sValue
}
}
var dbHandleQuery: FIRDatabaseHandle?
var dbrefString = (myDatabasePath)// this is the database path to the correct child
("MAIN LEAGUE")
dbHandleQuery=FIRDatabase.database().reference().child(dbrefString).queryOrdered(byChild: "Team Score").observe( .value, with: {(snapshot) in
var newContent : [content] = []
for snap in snapshot.children.allObjects as! [FIRDataSnapshot] {
let title = snap.key as String
let message = snap.value as? String
print(snap.key)
print(snap.value as Any)
newContent.append(content(sTitle: title, sValue: message as Any))
self.myTableView.reloadData()
}
self.cellContent = newContent
self.myTableView.reloadData()
})
How could I achieve that ranking? Or would it be better to try load everything in local arrays and then try rank them from there? Any help, greatly appreciated!
UPDATE: So the above does rank them correctly, but my table only retrieves the TEAM NAME, and I cannot extract the "Total Score" to put inside my tableview cell 2nd Label (it has 2 labels, 1 for Team Name, 1 for Total Score).
So now it looks like this :
" Team Bravo"
" Team Charlie"
" Team Alpha"
How can I attach each corresponding Total Score next to each one? Many thanks
Upvotes: 0
Views: 3150
Reputation: 406
Ok not sure this is the best possible answer, but I managed to make it work and get the result I wanted.
Posting it to help anyone who might run into the same issue:
dbHandleQuery = FIRDatabase.database().reference().child(dbrefString).queryOrdered(byChild: "Team Score").observe( .value, with: {(snapshot) in
var counter = 0
var newContent : [content] = []
for snap in snapshot.children.allObjects as! [FIRDataSnapshot] {
counter += 1
let title = snap.key as String
if let rankedBy = snap.value as? [String : Any] {
newContent.append(content(sTitle: "\(counter).\(title)", sValue: rankedBy["Team Score"] as Any))
self.myTableView.reloadData()
}
}
self.cellContent = newContent
self.myTableView.reloadData()
})
This gives me
"1.Team Bravo" - "200"
"2.Team Charlie" - "150"
"3.Team Alpha" - "50"
Upvotes: 4