top of page
Search

Presence System with Ionic and Firebase

  • Writer: Fire Focus
    Fire Focus
  • Sep 26, 2020
  • 2 min read

Updated: Sep 27, 2020



Introduction


In this lesson you will learn about how you can track user's presence with your app like Online,Offline,Away.


Here, we have three situations

  • Online - signed in and using app

  • Away - signed in but on different tab or minimizes the app

  • Offline - app closed

Detecting Connection State


For many presence-related features, it is useful for your app to know when it is online or offline. Firebase Realtime Database provides a special location at /.info/connected which is updated every time the Firebase Realtime Database client's connection state changes.


Base Info


I had list of users data in my project realtime database and a key called status to store presence of each user and display users using *ngFor.


Presence System


Whenever a user connects the app,this /.info/connected path keeps track of users presence.


Online and Offline Status


If user is connected, then updated the status key in users data in firebase database to online.

If user is disconnected from the app, onDisconnect() method is used to update the status of the user to offline.


presence.page.tssence.page.tspresence.page.ts

var user = firebase.auth().currentUser;
var myStatusRef = firebase.database().ref("users/"+user.uid+"/status");
var connectedRef = firebase.database().ref(".info/connected");

 connectedRef.on("value", function (snap) {
  if (snap.val() === true) {
  // We re connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
   var con = myStatusRef;
  // When app disconnect, remove this device
  con.onDisconnect().remove();
  //set status to online
  con.set("online");
  // When app disconnect, update the status to offline or last time I was seen online
  myStatusRef.onDisconnect().set("offline");        
  //or        
 myStatusRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
    }
});

Away Status


We check if the app’s browser tab is open using the Page Visibility API.Keep in mind, we are touching the DOM directly here, so this code will not work with server-side rendering or other non-web platforms.


presence.page.ts


document.onvisibilitychange = (e) => {
  if (document.visibilityState === "hidden") {
       myStatusRef .set('away');
      } else {
         myStatusRef .set('online');
      }
};

I hope you understand the lesson.Please leave your feedback in comments.Cheers!

Comments


Never Miss a Post. Subscribe Now!

Subscribe Fire Focus to get notified when we post something.Cheers!

Thanks for submitting!

"If you want something you've never had, you must be willing to do something you've never done"

bottom of page