Ondisconnect is fired if app goes to background mode

与世无争的帅哥 提交于 2019-12-01 12:28:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!