SwiftER
SwiftER

Reputation: 1255

Swift Firebase ondisconnect action when there is no internet

I have a user to user app. if the user lose internet connection I want firebase to query "isUserLogon:false". I use ondisconnect this work fine when the user terminate the app but not when they are disconnected from the internet. What is the best solution to resolve. Im assuming because there is no connection firebase cannot update. If the user is disconnected from the internet i don't want firebase to think they are still active when they are not, how do other apps handle this scenario.

let path = "rquest/frontEnd/users/\(self.currentUserId()!)"

        let myConnectionsRef = FIRDatabase.database().reference(withPath: path).child("isUserLogon")


        let lastOnlineRef = FIRDatabase.database().reference(withPath: path).child("lastOnline")

        let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")

        connectedRef.observe(.value, with: { snapshot in
            // only handle connection established (or I've reconnected after a loss of connection)
            guard let connected = snapshot.value as? Bool, connected else { return }

            // add this device to my connections list
            // this value could contain info about the device or a timestamp instead of just true
            let con = myConnectionsRef
            con.setValue(true)

            // when this device disconnects, remove it
            con.onDisconnectSetValue(false)

            // when I disconnect, update the last time I was seen online
            lastOnlineRef.onDisconnectSetValue("Date here")
        })

Upvotes: 1

Views: 1588

Answers (1)

BKS
BKS

Reputation: 153

This article explains how to build presence system to maintain online/offline status in firebase.

Essential steps to set up basic presence system:

var amOnline = new Firebase('https://<demo>.firebaseio.com/.info/connected');
var userRef = new Firebase('https://<demo>.firebaseio.com/presence/' + userid);
amOnline.on('value', function(snapshot) {
  if (snapshot.val()) {
    userRef.onDisconnect().remove();
    userRef.set(true);
  }
});

Thats it! now just make a call to below function passing uid of the users you want to know the network status. it returns either true/false based on their network availability.

 checkNetworkStatus(uid) {
        let userRef = this.rootRef.child('/presence/' + uid);
        return userRef.on('value', function (snapshot) {
            return snapshot.val();
        });
 }

Upvotes: 2

Related Questions