Search code examples
iosxcodeswiftfirebasechildren

Retrieving an array of children in Firebase using Swift


I have a database which looks something like this:

Firebase
 restaurants
  McDonalds
   Menu Item 1 : burger
   Menu Item 2 : fries
   Menu Item 3 : drink
  KFC
   Menu Item 1 : chicken
   Menu Item 2 : mashed potatoes
   Menu Item 3 : drink
  Taco Bell
   Menu Item 1 : taco
   Menu Item 2 : burrito
   Menu Item 3 : drink

How can I retrieve a list of only the restaurant names (array or dictionary is fine), without their respective menu items?

the output would ideally look something like ["McDonalds", "KFC", "Taco Bell"], with an accessible index or key.


Solution

  • You could do something like:

    var ref = Firebase(url: "https://<yourApp>.firebaseio.com/restaurants/")
    
    ref.observeEventType(.Value, withBlock: {
        snapshot in
        var restaurantNames = [String]()
        for restaurant in snapshot.children {
            restaurantNames.append(restaurant.key)
        }
        print(restaurantNames)
    })
    

    restaurantNames will have the array you asked for. You are still receiving the complete restaurant objects from firebase, but just using their keys(names).