Reputation: 153
I want to listen for childChanged
in my app. I have a firebaseStructure like this:
-counters
---currentLoggedInUsers : 4
I want to be able to listen to when currentLoggedInUsers changes.
My best effort is this:
ref?.child("counters").observe( .childChanged, with: { (snapshot) in
let dict = snapshot.value as? [String : Int] ?? [:]
print(snapshot) //Prints the correct value when updated
self.currentLoggedInUsers = dict["currentLoggedInUsers"]!
})
the snapshot
prints correctly when updated, but self. currentLoggedInUsers = dict["currentLoggedInUsers"]!
gives error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Upvotes: 0
Views: 47
Reputation: 35648
This answer will depend on whether there are other child nodes stored within counters. So if it just this
counters
currentLoggedInUsers: 2
then the following code should be used, keeping in mind that .value will cause the code in the closure to fire immediately.
let ref = self.ref.child("counters").child("currentLoggedInUsers")
ref.observe(.value, with: { snapshot in
print(snapshot.key, snapshot.value)
})
as it is watching that specific child node for changes.
note self.ref points to my firebase as a class var
To expand a bit, suppose you have other child nodes within counters and you want to watch them for changes as well.
counters
currentLoggedInUsers: 2
totalUsers: 100
usersFavFood: Tacos
and one way to handle that is
let ref = self.ref.child("counters")
ref.observe(.childChanged, with: { snapshot in
let nodeKey = snapshot.key
switch nodeKey {
case "currentLoggedInUsers":
let count = snapshot.value as? Int ?? 0
print("logged in users changed to: \(count)")
case "totalUsers":
let totalCount = snapshot.value as? Int ?? 0
print("total Users: \(totalCount)")
case "usersFavFood":
let food = snapshot.value as? String ?? "No food for you"
print("favorite food changed to: \(food)")
default:
print("some node changed but it's not handled")
}
})
Upvotes: 2