doomsweb
doomsweb

Reputation: 63

Swift - Read Data from Firebase (Realtime-Database)

im completely new in Xcode Development.

I have created the following database in my Firebase:

{
  "Bicycle" : {
    "BMX" : {
      "image" : "bmx.png",
      "text" : "BMX ..."
    },
    "Dirt jumping" : {
      "image" : "dirtjumping.png",
      "text" : "Dirt jumping..."
    }
  },
  "Running" : {
    "Half-marathon" : {
      "image" : "halfmarathon.png",
      "text" : "Half-marathon ..."
    },
    "Marathon" : {
      "image" : "marathon.png",
      "text" : "Marathon ..."
    }
  }
}

Now I want to show "Bicycle" and "Running" in the first TableViewController.

When I try the following code:

var ref: DatabaseReference!
ref = Database.database().reference()

ref.child("sports").observeSingleEvent(of: .value) { snapshot in
    print(snapshot.childrenCount) // I got the expected number of items
    for case let rest as DataSnapshot in snapshot.children {
        print(rest.children)
    }
}

I get the following output:

2
<FTransformedEnumerator: 0x6000038b40a0>
<FTransformedEnumerator: 0x6000038b40a0>

Maybe you can give me a good tip.

Kind regards, doomsweb

Upvotes: 1

Views: 335

Answers (2)

Dinesh Choudhary
Dinesh Choudhary

Reputation: 73

You can use snapshot.valueInExportFormat() to get data in dictionary format.

Upvotes: 0

RajeshKumar R
RajeshKumar R

Reputation: 15748

Get snapshot.value as Dictionary and get the details from the dictionary

ref.child("sports").observeSingleEvent(of: .value, with: { snapshot in
    if let sports = snapshot.value as? [String: Any] { 
        for (title, details) in sports {
            print(title)//Bicycle
            print(details)//["BMX" : ["image" : "bmx.png", "text" : "BMX ..."], "Dirt jumping" : ["image" : "dirtjumping.png","text" : "Dirt jumping..."]]
        }
    }
}) { (error) in
    print(error.localizedDescription)
}

Upvotes: 1

Related Questions