user10536150
user10536150

Reputation:

How to get firebase child snapshot value back to work?

var test = String()

func fetchUser() {
 let currentUserUid = Auth.auth().currentUser?.uid

    Database.database().reference().child("users").child(currentUserUid!).child("test").observeSingleEvent(of: .value) { (snapshot) in

        self.test = snapshot.value as! String
   })   
}     

I want to add the snapshot value to my variable.

But it is crashing, although my firebase concept is perfect and fitting to the code.

What could be the reason?

Console structure:

The error i get: Could not cast value of type 'NSNull' (0x10dd86de0) to 'NSString' (0x10b2485d8).

In addition i would like to add that i once renamed the child name from "test" to sth else and it worked afterwards for a short time. Than the error occured again.

Upvotes: 1

Views: 90

Answers (1)

Jay
Jay

Reputation: 35667

There are a number of typo's in the code in the question but it's kinda correct.

The biggest issue is the handling of optionals - they are being force-unwrapped when you should be treating them as optionals to protect your code.

so this

let currentUserUid = Auth.auth().currentUser?.uid

would be better as

guard let user = Auth.auth().currentUser else {return}
let uid = user.uid

But working with your code, here's an update that reads the value from that node as a string and prints it out.

var test = String()

func readUserString() {
    let currentUserUid = "iBagi96IMGbd2k6wUtXjPs0gmNq1"
    let usersRef = self.ref.child("users")
    usersRef.child(currentUserUid).child("test").observeSingleEvent(of: .value, with: { snapshot in
        let test = snapshot.value as! String
        print(test) //prints "testValue"
    })
}

Upvotes: 2

Related Questions