0

I want to get a specific value from Firebase Database with child name "totalExercise" and print it using swift. Here is the current content of firebase database.

enter image description here

And here is my code in swift trying to get and print the totalExercise value

enter image description here

4
  • I think it is because your node title is, effectively, optional. Which, in itself isn’t a problem, but you are unwrapping it when you are querying Firebase by using (user?.uid)! Commented Nov 29, 2017 at 8:47
  • In the future, please use text versions of your firebase structure and code instead of screen shots so we can use that in our answer without having to retype it. You can get Firebase as text using the Firebase Console->Export JSON and then you can copy/paste your structure and code in your question. Commented Nov 29, 2017 at 22:51
  • @Paulo yes you are right.Thank you very much. Commented Dec 2, 2017 at 3:42
  • @Jay Yes I will post as a text next time. It was my first time posting a question here so I was not familiar to the custom here but yeah thanks for the feedback. I will keep it in mind. Commented Dec 2, 2017 at 3:44

1 Answer 1

1

This is a literal answer to your question but please read on

let loginRef = self.ref.child("fblogintest-35707").child("Optional(\"gl8...\")")

loginRef.observeSingleEvent(of: .value, with: { snapshot in
    let val = snapshot.value as! [String: Any]
    let te = val["totalExercise"]
    print(te)
})

the gl8 is a long string which I didnt feel like retyping so just insert that from your question. This code will print '10'

That being said, there are a number of issues with the Firebase structure and the code in the question.

As you can see, whatever the code is that's creating the keys in your question is creating them as Optionals and that should not be done as the actual string of "Optional("gl8..") is being written to Firebase.. That's why you see the word Optional in your structure.

You should probably do some unwrapping/error checking on ref? and user? as well so if they are nil (they are optionals) the code doesn't crash.

If you haven't done so, read up on Optionals as they are super powerful but you got to wrap your brain around how to implement them effectively to protect your code.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much.your code answer was very helpful and it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.