如何创建用户上次在线的“上次查看时间”?

2024-02-21

我想添加一个last seen at today 1pm或者用户上次访问或打开我的应用程序的时间 - WhatsApp 和其他聊天应用程序具有的功能。

在我的 React Native 聊天应用程序中,我使用 redux 进行状态处理。我正在使用 Firebase 作为我的后端。我的聊天应用程序即将完成,但我不知道如何添加用户上次查看的功能。


您可以使用 Firebase 实时数据库断开连接 API https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect建立一个存在系统,例如检测用户上次在线的时间。

以下示例包含用户状态,例如online or offline, 以及ASAlast_changed时间戳。您可以结合使用这两者来为聊天应用程序中的每个用户创建丰富的在线状态。

import firebase from 'react-native-firebase';

// Fetch the current user's ID from Firebase Authentication.
const uid = firebase.auth().currentUser.uid;

// Create a reference to this user's specific status node.
// This is where we will store data about being online/offline.
const userStatusRef = firebase.database().ref('/status/' + uid);

// We'll create two constants which we will write to 
// the Realtime database when this device is offline
// or online.
const isOfflineForDatabase = {
    state: 'offline',
    last_changed: firebase.database.ServerValue.TIMESTAMP,
};

const isOnlineForDatabase = {
    state: 'online',
    last_changed: firebase.database.ServerValue.TIMESTAMP,
};

// Create a reference to the special '.info/connected' path in 
// Realtime Database. This path returns `true` when connected
// and `false` when disconnected.
firebase.database().ref('.info/connected').on('value', (snapshot) => {
    // If we're not currently connected, don't do anything.
    if (snapshot.val() == false) {
        return;
    };

    // If we are currently connected, then use the 'onDisconnect()' 
    // method to add a set which will only trigger once this 
    // client has disconnected by closing the app, 
    // losing internet, or any other means.
    userStatusRef.onDisconnect().set(isOfflineForDatabase).then(() => {
        // The promise returned from .onDisconnect().set() will
        // resolve as soon as the server acknowledges the onDisconnect() 
        // request, NOT once we've actually disconnected:
        // https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect

        // We can now safely set ourselves as 'online' knowing that the
        // server will mark us as offline once we lose connection.
        userStatusRef.set(isOnlineForDatabase);
    });
});

示例代码改编自:状态指南 - Firebase 网站 https://firebase.google.com/docs/firestore/solutions/presence.

希望有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何创建用户上次在线的“上次查看时间”? 的相关文章

随机推荐