2016-11-23 74 views
2

我的数据库结构如下:火力地堡数据库 - 如何斯威夫特词典获取从多个子节点和存储子值

"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 namenumber 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) 

回答

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) 

如果其他人有类似的问题,我希望这有助于提供一种访问值的方法的想法。