我在firebase中有三個節點,我想通過使用相同的循環來循環。我能夠成功地遍歷單個節點使用此代碼(餅乾):如何在同一個循環中一次循環所有Firebase子項?
databaseRef.child("cookies").observeSingleEvent(of: .value, with: {(snapshot) in
for item in snapshot.children.allObjects as! [DataSnapshot] {
let thisItem = item.value as! NSDictionary
if(favoriteArray.contains(item.key)) {
self.numberOfRecipes.append(thisItem["recipeHeaderFirebase"] as! String)
let tempRecipe = Recipe()
tempRecipe.fbKey = item.key
tempRecipe.recipeHeaderObject = (thisItem["recipeHeaderFirebase"] as! String)
tempRecipe.recipeTextObject = (thisItem["recipeIngredientsTextFirebase"] as! String)
tempRecipe.recipeImageObject = (thisItem["recipeImageFirebase"] as! String)
self.recipeClassArray.append(tempRecipe)
}
}
})
我現在想循環剩下的兩個節點爲好。有任何想法嗎?
我試着添加額外的節點,但控制檯中的打印顯示它只從最後一個節點添加。請參閱以下代碼:
self.databaseRef.child("cookies").observeSingleEvent(of: .value, with: {(snapshot) in
self.databaseRef.child("dessert").observeSingleEvent(of: .value, with: {(snapshot) in self.databaseRef.child("breakfast").observeSingleEvent(of: .value, with: {(snapshot) in
for item in snapshot.children.allObjects as! [DataSnapshot] {
let thisItem = item.value as! NSDictionary
if(favoriteArray.contains(item.key)) {
self.numberOfRecipes.append(thisItem["recipeHeaderFirebase"] as! String)
let tempRecipe = Recipe()
tempRecipe.fbKey = item.key
tempRecipe.recipeHeaderObject = (thisItem["recipeHeaderFirebase"] as! String)
tempRecipe.recipeTextObject = (thisItem["recipeIngredientsTextFirebase"] as! String)
tempRecipe.recipeImageObject = (thisItem["recipeImageFirebase"] as! String)
self.recipeClassArray.append(tempRecipe)
}
}
print(self.numberOfRecipes.count)
print(self.recipeClassArray)
let url = URL(string: self.recipeClassArray[self.currentView].recipeImageObject)
self.recipeImageUI.kf.setImage(with: url) //SÄTTER IN BILD MED KINGFISHER
self.recipeHeader.text = self.recipeClassArray[self.currentView].recipeHeaderObject //SÄTTER IN HEADER
self.ingredientText.text = self.recipeClassArray[self.currentView].recipeTextObject //SÄTTER IN TEXTEN
self.animateFunc(image: self.recipeImageUI, labelHeader: self.recipeHeader, labelText: self.ingredientText) //FUNKTION FÖR ATT ANIMERA
})
})
})
您可以嵌入在觀察到對方。例如,類似這樣的東西:databaseRef.child(「cookies」)。observeSingleEvent(of:.value,with:{(snapshot)in databaseRef.child(「secondNode」)。observeSingleEvent(of:.value,with:{快照)in ...等等。這在技術上不是一個循環,而是數據訪問一個接一個地發生 –
謝謝,但我在控制檯中做了一個打印,它似乎只是從最後一個節點添加,忽略了前兩個列出...更新我的帖子上面:)你能看到缺少的東西嗎? –
是的,因爲打印只能在最深層次上調用...所以嘗試這樣的事情:self.databaseRef.child(「cookies」)。observeSingleEvent(的:.value的,具有:{(cookiesSnapshot)在 \t \t打印( 「曲奇:\(cookiesSnapshot)」) \t \t self.databaseRef.child( 「甜點」)observeSingleEvent(的:。價值,具有:{ (dessertSn apshot)在 \t \t \t打印( 「甜點:\(dessertSnapshot)」) \t \t \t self.databaseRef.child( 「早餐」)observeSingleEvent(作者:.value的,有:{(breakfastSnapshot)在 \t \t \t print(「早餐:\(早餐快照)」) –