问题
I have the following code:
func OnlineStatus(userID: String){
handle = Auth.auth().addStateDidChangeListener { (auth, user) in
if let user = user {
// User is signed in.
self.UID = user.uid
self.connectedRef.observe(.value, with: { snapshot in
if let connected = snapshot.value as? Bool, connected {
// print("############################ Connected")
self.ref.child(self.UID!).child("OnlineStatus").setValue("ON")
} else {
// print("############################ Not connected")
self.ref.child(self.UID!).child("OnlineStatus").setValue("OFF")
}
self.ref.child(self.UID!).child("OnlineStatus").onDisconnectSetValue("OFF")
})
}}
}
The function will be triggered in viewWillAppear. The idea is to build a simple presence system. For some reason onDisconnect gets fired when I send the app to background and than send my iPhone to sleep. I actually would like that online status goes to off only when user logs out or looses internet connection. What is wrong with my code or settings?
回答1:
The onDisconnect
event fires when the client disconnects from the Firebase Database servers, and that happens when your app goes to the background. There is no difference from Firebase's perspective between the user being on train that drives into a tunnel, and their phone going to sleep. In both cases the connection between the client and the server gets dropped, so the onDisconnect()
fires.
You'll typically end up using .info/connected
and onDisconnect()
to set a value of when the user was last seen, while using onAuthStateChanged()
to set a status flag of the user being signed in. Then you show the list of users by first showing users that are signed in, in the order of how recently they were active.
来源:https://stackoverflow.com/questions/48177034/ondisconnect-is-fired-if-app-goes-to-background-mode