【问题标题】:How do I create a 'last seen at' time of when a user was last online?如何创建用户最后一次在线的“最后一次看到”时间?
【发布时间】:2019-01-18 10:15:15
【问题描述】:

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

在我的 React Native 聊天应用程序中,我使用 redux 进行状态处理。我在后端使用 Firebase。我的聊天应用快完成了,但我不知道如何添加用户最后一次看到的功能。

【问题讨论】:

  • 您可能会因为提出问题而被标记,因为它不符合 Stack Overflow 的良好格式。完全可以理解,因为你是新来的!您应该使用以下内容编辑问题: 1. 描述您要解决的确切问题(我不知道“最后一次看到”是什么意思)。 2. 描述你迄今为止尝试过的研究和方法。 3. 问一个关于实施的具体问题——目前你的问题有点模糊。 4. 提供有关您的应用程序设置方式的信息(例如您的聊天数据模型)。信息太少,我们帮不了你:)

标签: react-native react-native-android react-native-ios react-native-firebase


【解决方案1】:

您可以使用 Firebase 实时数据库 onDisconnect API 来构建在线状态系统,例如检测用户上次在线的时间。

以下示例包含用户状态,例如onlineoffline,以及 last_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);
    });
});

示例代码改编自:presence guide - Firebase website

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    相关资源
    最近更新 更多