LachlanMx
LachlanMx

Reputation: 15

My firebase int returns nil

I'm trying to pull an int from my firebase db however when I try and set my variable it returns nil.

ref = Database.database().reference()    
let UserUID = Auth.auth().currentUser?.uid as? String

ref.child("users").child(UserUID!).child("MaxVal").observeSingleEvent(of:
.value, with: { (snapshot) in

            let snap = snapshot.value as? Int
            self.MaxValFB = snap! //this returns nil

    }) { (error) in
        print(error.localizedDescription)
    }

Any help apreiciated!

EDIT: upon printing its result it returns Optional( null)

also here is the db json file { "users" : { "Optional(\"njcfCQaIIhZS9qrqM9OFLqTS7yA2\")" : { "MaxVal" : 1 } } }

Upvotes: 1

Views: 57

Answers (1)

3stud1ant3
3stud1ant3

Reputation: 3606

I think the problem is this "Optional(\"njcfCQaIIhZS9qrqM9OFLqTS7yA2\")" , when you are saving the data to firebase , you are giving it the id without unwrapping the optional and when you get the value you are unwrapping it like UserUID! , so it gives "njcfCQaIIhZS9qrqM9OFLqTS7yA2" , hence these are two different values.

So I think you should unwrap the userid when you save the data to firebase or try to get it without unwrapping i.e child(UserUID) without ! , although I would suggest to go with the first option.

Upvotes: 1

Related Questions