How do you check for online presence in Unity with Firebase Realtime Database?

Viewed 60

Problem:

I've read and tried a few different iterations of the "Build Presence..." documentation found here and elsewhere: https://firebase.google.com/docs/firestore/solutions/presence, but have been unable to have a proper disconnect action taken upon a user losing their internet connection. There is a similar post, but the question is not answered using what I think to be the true intent of OnDisconnect (but I could certainly be wrong in my understanding).

Goal:

Upon a user losing their connection to the internet, or other unanticipated DC, the "online" value for that user should be set to "F".

Question:

Does anyone have suggestions on how to properly code a presence check system in Unity with Firebase, or can point out what I've done incorrectly in the code below?

Background Info:

My Firebase Realtime Database currently has no limitations on reads/writes.

Here is sample code that I've tried. It works properly upon forced application closed (i.e. end process action), but does not work when a user DCs from the internet. I've let it sit for several minutes after DCing to ensure it was not just a server delay issue.

private void Start() //removed some unrelated lines of code from this method
{
        PresenceCheck();
}

public void PresenceCheck() //listen for change
{

    var connectCheck = FirebaseDatabase.DefaultInstance.GetReference(".info/connected");
    connectCheck.ValueChanged += CheckForDisconnect;
}

private void CheckForDisconnect(object sender, ValueChangedEventArgs args)
{
    var checkBool = args.Snapshot;

    if (checkBool == null) //if null, do nothing for now
    {
        return;
    }
    else if ((bool)checkBool.GetValue(true)) //if connected, set online to "T" and on disconnect set online value to "F"
    {
        FirebaseDatabase.DefaultInstance.GetReference("users").Child(userID).Child("online").OnDisconnect().SetValue("F");
        FirebaseDatabase.DefaultInstance.GetReference("users").Child(userID).Child("online").SetValueAsync("T");
    }
}
0 Answers
Related