John
John

Reputation: 4018

How to read data from firebase

This is my realtime database structure. I have only 1 item in club. In reality, I have many items.

enter image description here

I want to read all clubs information, and try to get the related address using club's key.

here is my code:

func loadClubs() {

        ref = Database.database().reference()
        let clubRef = ref.child("club")
        let refHandle = clubRef.observe(DataEventType.value, with: { (snapshot) in
            if let c = snapshot.value as? [String : AnyObject] {
                let name = c["name"] as! String // PRINT NIL



            }

            // ...
        })
    }

How can I retrieve a club's name, courtNum, explanation,...?

Upvotes: 3

Views: 1547

Answers (1)

Pushpendra
Pushpendra

Reputation: 986

try this:-

ref = Database.database().reference()

ref.child("club").observe(.value, with: { (snapshot) in
print("clubs: \(snapshot)")

if(snapshot.exists()) {
    let array:NSArray = snapshot.children.allObjects as NSArray

    for obj in array {
        let snapshot:FIRDataSnapshot = obj as! FIRDataSnapshot
        if let childSnapshot = snapshot.value as? [String : AnyObject] 
             {
            if let clubName = childSnapshot["name"] as? String {
                print(clubName)
            }
        }
    }

}
 }

Upvotes: 4

Related Questions