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:
- users
- iBagi96IMGbd2k6wUtXjPs0gmNq1. <--- currentUserUid
- test: testValue
- iBagi96IMGbd2k6wUtXjPs0gmNq1. <--- currentUserUid
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.
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
would be better as
But working with your code, here's an update that reads the value from that node as a string and prints it out.