如何创建用户上次在线的"上次上线时间"?



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

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

您可以使用Firebase Realtime Databases 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);
});
});

示例代码改编自:状态指南 - Firebase 网站。

希望有帮助。

相关内容

  • 没有找到相关文章

最新更新