How do I loop all Firebase children at once in the same loop?

后端 未结 2 1559
天命终不由人
天命终不由人 2021-01-24 21:07

I have three nodes in firebase that I would like to loop through using the same loop. I\'m successfully able to loop through a single node (cookies) using this code:

<         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 21:54

    You can convert snapshot to dict and loop through the dict:

    databaseRef.child("cookies").observeSingleEvent(of: .value, with: { snapshot in
        if let dict = snapshot.value as? Dictionary> {
            for (key, value) in dict {
                if let recipeHeader = value["recipeHeaderFirebase"] as? String, favoriteArray.contains(key) {
                    self.numberOfRecipes.append(recipeHeader)
                 ...
                }
            }
        }
    }
    

    or you can use the enumerator:

    databaseRef.child("cookies").observeSingleEvent(of: .value, with: { snapshot in
        let enumerator = snapshot.children
        while let (key, value) = enumerator.nextObject() as? FIRDataSnapshot {
            if let recipeHeader = value["recipeHeaderFirebase"] as? String, favoriteArray.contains(key) {
                self.numberOfRecipes.append(recipeHeader)
                ...
            }
        }
    }
    

提交回复
热议问题