How to retrieve firebase database properly?

By : ndduong
Source: Stackoverflow.com
Question!

I am trying to retrieve the data from firebase database. However, I cannot get my local variables assigned to the values of the database. I am using the following classes and methods.

class Episode {

var title: String?
var description: String?
var location: String?
var discount: String?
var star: Int?

init() {
    self.title = ""
    self.description = ""
    self.location = ""
    self.discount = ""
    self.star = 0
}

This is my method for pulling the data from the databse

func getValues() -> Episode {
    let rootRef = FIRDatabase.database().reference().child("Restaurants").child("The Kafe")
    let descriptionRef = rootRef.child("Description")
    let discountRef = rootRef.child("Discount")
    let locationRef = rootRef.child("Location")
    let starRef = rootRef.child("Star")
    let episode = Episode()

    descriptionRef.observeEventType(.Value) { (snap: FIRDataSnapshot) in
        episode.description = snap.value as? String
    }
    discountRef.observeEventType(.Value) { (snap: FIRDataSnapshot) in
        episode.discount = snap.value as? String
    }
    locationRef.observeEventType(.Value) { (snap: FIRDataSnapshot) in
        episode.location = snap.value as? String
    }
    starRef.observeEventType(.Value) { (snap: FIRDataSnapshot) in
        episode.star = snap.value as? Int
        print(episode.description!)
    }
    return episode
}

When I print out the values of the returned episode, they are all empty. However, when I print the values within the closure itself (Eg. if I do print(episode.description) within the obserEventType closure, it works fine. But if I print it outside it is empty.

I think I am missing something fundamental about swift or firebase. I am new to iOS programming so any help would be greatly appreciated.

By : ndduong


Answers

Only inside the first observer you will have the value the return will always be nil, that is because only the return is trying to work in a sync way while firebase will always work in an async way

rootRef.observeEventType(.Value, withBlock: {(snap) in
        let ep: Dictionary
By : Ymmanuel


This video can help you solving your question :)
By: admin