SwiftUI Firebase RealTime Database doesn't retrieve value

Hey,


I'm a beginner hobby dev who tried cloud storage for first time using SwiftUI.

I wanted to make a simple app which only needs to retrieve some values of a Database.

I'm using Firebase RealTime Database.


My Database structure looks like this:

monsterhunter-e8167

  • Velkhana
    • HP: 12000
    • element: Ice
  • Rath
    • HP: 8000
    • element: Fire


My Code looks like this:


import SwiftUI
import FirebaseDatabase


struct ContentView: View {

    var ref: DatabaseReference = Database.database().reference()
    var body: some View {
        Button(action: {
            self.ref.child("monsterhunter-e8167").child("Velkhana")
                .observeSingleEvent(of: .value, with: { (snapshot) in
      
              let value = snapshot.value as? NSDictionary
              let hp = value?["HP"] as? Int ?? 0
    
              print(hp)

              // ...
              }) { (error) in
                print(error.localizedDescription)
            }
        }) {
            Text("print")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}



However it is printing out

0



the expected output should be:

12000


I figured out "value" is nil but I don't know why.

"childpath" should be correct

Can anyone tell me what I'm doing wrong?

You mean line 16 prints 0 ?


That effectively means :

value?["HP"] as? Int

is nil.


Could you add a print on line 15:


print("snapshot.value", snapshot.value)
print("value", value)
print("value?[HP]", value?["HP"])



From Firebase doc, I read that you get an NSNumber, not an Int.


So, may be (I'm not practicing Firebase, so take it with some precaution) you should write


var hp = 0
let number : NSNumber? = value?["HP"] as? NSNumber
if let integerValue = number?.intValue {
    hp = integerValue
}

thanks for the reply.

The output of the print statements showed me the following things:

snapshot.value Optional()
value nil
value?[HP] nil



Also I added the other piece of code. The output was also

0
SwiftUI Firebase RealTime Database doesn't retrieve value
 
 
Q