KP.
KP.

Reputation: 186

Assign Firebase snapshot to a variable

I am trying to save info that I am reading from my Firebase Database into a variable. This is the way I am reading my info:

dbHandle = dbReference?.child("users").child(userEmail!).child("state").observe(.value, with: { (snapshot) in
        if let userState = (snapshot.value as? String){
            var taxRate = self.stateAbbreviations[userState]!
            print(taxRate)
        }

    })

My question is now how do I make userState & taxRate visible outside of this call?

I have tried declaring userState outside of the call, initializing it within, and referencing it outside again but it doesn't work. For example:

var userState:String? = ""
dbHandle = dbReference?.child("users").child(userEmail!).child("state").observe(.value, with: { (snapshot) in
        let userState = (snapshot.value as? String)
        var taxRate = self.stateAbbreviations[userState]!
        print(taxRate)
    })
print(userState)

But it only prints out ""

Any advice??

Upvotes: 0

Views: 568

Answers (1)

Francesco Deliro
Francesco Deliro

Reputation: 3939

You are initializing a var userState as an empty string and your print outside the completion retrieve its default value, in your firebase completion you are initializing another userState variable with let userState =

If you want to use userState and taxRate outside the call you can do it in this way, for example:

// Create your variables 
var userState: String = “”

//Create a func with completion handler
func getUserStateAndTaxRate(completion:((String,String) -> Void)?) {
    dbHandle = dbReference?.child("users").child(userEmail!).child("state").observe(.value, with: { (snapshot) in
        let userState = (snapshot.value as? String)
        var taxRate = self.stateAbbreviations[userState]!
        print(taxRate)
        completion?(userState, taxRate)
    })
}

//Then call it
getUserStateAndTaxRate { (userState, taxRate) in 
    // userState and taxRate are now available 
    self.userState = userState 
    self.taxRate = taxRate 
}

Upvotes: 1

Related Questions