2016-11-23 78 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) 

如果其他人有類似的問題,我希望這有助於提供一種訪問值的方法的想法。