我的数据库结构如下:
"routines": {
"users unique identifier": {
"routine unique identifier": {
"routine_name": "routine name",
"routine_create_date": "routine created date",
"exercises": {
"exercise name": {
"Sets": "number of sets"
}
}
}
}
}
检索数据时,我希望将每个routine
存储为要加载到UITableView
的对象。我正在使用的例程结构是:
struct Routine {
var routineName: String!
var routineExercisesAndSets: [String:Int]!
}
如何从中检索值,以便对于每个Routine
模型我可以Routine(routineName: "Legs", routineExercisesAndSets: ["Squats":4,"Lunges":4,"Calf Raises":4])
,其中练习字典为exercise name
:number of sets
。
我目前正在使用不同的结构,几乎可以得到我想要的结果:
let ref = FIRDatabase.database().reference().child("routines").child(userId)
var routineTemp = Routine()
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
routineTemp.routineName = dictionary["routineName"] as! String
let enumerator = snapshot.childSnapshot(forPath: "exercises").children
var exercisesAndSets = [String:Int]()
while let item = enumerator.nextObject() as? FIRDataSnapshot {
exercisesAndSets[item.key] = item.value! as? Int
}
routineTemp.routineExercisesAndSets = exercisesAndSets
print(routineTemp)
}
} , withCancel: nil)
答案 0 :(得分:2)
我设法使用以下代码获取每个练习的值及其各自的numberOfSets
:
guard let userId = FIRAuth.auth()?.currentUser?.uid else {
return
}
let ref = FIRDatabase.database().reference().child("routines").child(userId)
var routineTemp = Routine()
var exercisesAndSets = [String:Int]()
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
routineTemp.routineName = dictionary["routineName"] as! String
let enumerator = snapshot.childSnapshot(forPath: "exercises").children
while let item = enumerator.nextObject() as? FIRDataSnapshot {
exercisesAndSets[item.key] = item.childSnapshot(forPath: "numberOfSets").value! as? Int
}
}
routineTemp.routineExercisesAndSets = exercisesAndSets
self.routines.append(routineTemp)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} , withCancel: nil)
如果其他人遇到类似的问题,我希望这有助于提供一种访问价值的方法。