با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
بسته به نوع برنامهای که میسازید، تشخیص اینکه کدام یک از کاربران یا دستگاههای شما فعالانه آنلاین هستند، ممکن است مفید باشد - در غیر این صورت به عنوان تشخیص «حضور» شناخته میشود.
به عنوان مثال، اگر در حال ساخت اپلیکیشنی مانند یک شبکه اجتماعی یا استقرار ناوگانی از دستگاه های اینترنت اشیا هستید، می توانید از این اطلاعات برای نمایش لیستی از دوستانی که آنلاین و رایگان برای چت هستند استفاده کنید، یا دستگاه های اینترنت اشیا خود را بر اساس «آخرین بازدید» مرتب کنید.
Cloud Firestore به طور بومی از حضور پشتیبانی نمیکند، اما میتوانید از سایر محصولات Firebase برای ایجاد یک سیستم حضور استفاده کنید.
راه حل: توابع ابر با پایگاه داده بیدرنگ
برای اتصال Cloud Firestore به ویژگی حضور بومی پایگاه داده بیدرنگ Firebase، از Cloud Functions استفاده کنید.
از پایگاه داده بیدرنگ برای گزارش وضعیت اتصال استفاده کنید، سپس از Cloud Functions برای منعکس کردن آن داده ها در Cloud Firestore استفاده کنید.
استفاده از حضور در پایگاه داده بیدرنگ
ابتدا، نحوه عملکرد یک سیستم حضور سنتی در پایگاه داده Realtime را در نظر بگیرید.
وب
// Fetch the current user's ID from Firebase Authentication.varuid=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.varuserStatusDatabaseRef=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.varisOfflineForDatabase={state:'offline',last_changed:firebase.database.ServerValue.TIMESTAMP,};varisOnlineForDatabase={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',function(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.userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function(){// 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.userStatusDatabaseRef.set(isOnlineForDatabase);});});
این مثال یک سیستم حضوری کامل در پایگاه داده Realtime است. چندین قطع اتصال، خرابی و غیره را کنترل می کند.
اتصال به Cloud Firestore
برای پیاده سازی راه حل مشابه در Cloud Firestore از همان کد Realtime Database استفاده کنید، سپس از Cloud Functions برای همگام نگه داشتن پایگاه داده Realtime و Cloud Firestore استفاده کنید.
اگر قبلاً این کار را نکردهاید، پایگاه داده Realtime را به پروژه خود اضافه کنید و راه حل حضور بالا را در آن قرار دهید.
در مرحله بعد وضعیت حضور را با روش های زیر با Cloud Firestore همگام می کنید:
به صورت محلی، به حافظه پنهان Cloud Firestore دستگاه آفلاین، به طوری که برنامه بداند آفلاین است.
در سطح جهانی، از یک تابع Cloud استفاده کنید تا همه دستگاههای دیگری که به Cloud Firestore دسترسی دارند بدانند این دستگاه خاص آفلاین است.
به روز رسانی کش محلی Cloud Firestore
بیایید نگاهی به تغییرات مورد نیاز برای انجام اولین مسئله بیاندازیم - بهروزرسانی حافظه پنهان محلی Cloud Firestore .
وب
// ...varuserStatusFirestoreRef=firebase.firestore().doc('/status/'+uid);// Firestore uses a different server timestamp value, so we'll // create two more constants for Firestore state.varisOfflineForFirestore={state:'offline',last_changed:firebase.firestore.FieldValue.serverTimestamp(),};varisOnlineForFirestore={state:'online',last_changed:firebase.firestore.FieldValue.serverTimestamp(),};firebase.database().ref('.info/connected').on('value',function(snapshot){if(snapshot.val()==false){// Instead of simply returning, we'll also set Firestore's state// to 'offline'. This ensures that our Firestore cache is aware// of the switch to 'offline.'userStatusFirestoreRef.set(isOfflineForFirestore);return;};userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function(){userStatusDatabaseRef.set(isOnlineForDatabase);// We'll also add Firestore set here for when we come online.userStatusFirestoreRef.set(isOnlineForFirestore);});});
با این تغییرات، اکنون اطمینان دادهایم که وضعیت محلیCloud Firestore همیشه وضعیت آنلاین/آفلاین دستگاه را منعکس میکند. این بدان معناست که میتوانید به سند /status/{uid} گوش دهید و از دادهها برای تغییر رابط کاربری خود برای نشان دادن وضعیت اتصال استفاده کنید.
وب
userStatusFirestoreRef.onSnapshot(function(doc){varisOnline=doc.data().state=='online';// ... use isOnline});
اگرچه برنامه ما به درستی حضور آنلاین را به خود گزارش میدهد، اما این وضعیت هنوز در سایر برنامههای Cloud Firestore دقیق نخواهد بود زیرا نوشتن وضعیت «آفلاین» ما فقط محلی است و با بازیابی اتصال همگامسازی نمیشود. برای مقابله با این، از یک Cloud Function استفاده می کنیم که مسیر status/{uid} را در پایگاه داده بیدرنگ مشاهده می کند. هنگامی که مقدار پایگاه داده بیدرنگ تغییر می کند، مقدار با Cloud Firestore همگام می شود تا وضعیت همه کاربران صحیح باشد.
Node.js
firebase.firestore().collection('status').where('state','==','online').onSnapshot(function(snapshot){snapshot.docChanges().forEach(function(change){if(change.type==='added'){varmsg='User '+change.doc.id+' is online.';console.log(msg);// ...}if(change.type==='removed'){varmsg='User '+change.doc.id+' is offline.';console.log(msg);// ...}});});
پس از استقرار این تابع، یک سیستم حضور کامل در حال اجرا با Cloud Firestore خواهید داشت. در زیر نمونه ای از نظارت برای کاربرانی که آنلاین یا آفلاین هستند با استفاده از پرس و جو where() است.
وب
firebase.firestore().collection('status').where('state','==','online').onSnapshot(function(snapshot){snapshot.docChanges().forEach(function(change){if(change.type==='added'){varmsg='User '+change.doc.id+' is online.';console.log(msg);// ...}if(change.type==='removed'){varmsg='User '+change.doc.id+' is offline.';console.log(msg);// ...}});});
استفاده از پایگاه داده بیدرنگ برای افزودن حضور به برنامه Cloud Firestore مقیاس پذیر و موثر است اما دارای محدودیت هایی است:
Debouncing - هنگام گوش دادن به تغییرات بلادرنگ در Cloud Firestore ، این راه حل احتمالاً تغییرات متعددی را ایجاد می کند. اگر این تغییرات بیش از آنچه میخواهید رویدادها را راهاندازی میکنند، رویدادهای Cloud Firestore را به صورت دستی حذف کنید.
اتصال - این پیاده سازی اتصال به پایگاه داده بیدرنگ را اندازه گیری می کند، نه به Cloud Firestore . اگر وضعیت اتصال به هر پایگاه داده یکسان نباشد، این راه حل ممکن است وضعیت حضور نادرست را گزارش کند.
Android - در Android، پایگاه داده Realtime پس از 60 ثانیه عدم فعالیت، از Backend قطع می شود. عدم فعالیت به این معنی است که شنوندگان باز یا عملیات معلق وجود نداشته باشند. برای باز نگه داشتن اتصال، توصیه میکنیم یک شنونده رویداد ارزشی به مسیری علاوه بر .info/connected اضافه کنید. برای مثال میتوانید FirebaseDatabase.getInstance().getReference((new Date()).toString()).keepSynced() در شروع هر جلسه انجام دهید. برای اطلاعات بیشتر، به تشخیص وضعیت اتصال مراجعه کنید.
تاریخ آخرین بهروزرسانی 2025-09-04 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-09-04 بهوقت ساعت هماهنگ جهانی."],[],[],null,["\u003cbr /\u003e\n\nDepending on the type of app you're building, you might find it useful to detect\nwhich of your users or devices are actively online --- otherwise known as\ndetecting \"presence.\"\n\nFor example, if you're building an app like a social network or deploying a\nfleet of IoT devices, you could use this information to display a list of\nfriends that are online and free to chat, or sort your IoT devices by\n\"last seen.\"\n\nCloud Firestore doesn't natively support presence, but you can\nleverage other Firebase products to build a presence system.\n\nSolution: Cloud Functions with Realtime Database\n\nTo connect Cloud Firestore to Firebase Realtime Database's native\npresence feature, use Cloud Functions.\n\nUse Realtime Database to report connection status, then use Cloud Functions to\nmirror that data into Cloud Firestore.\n\nUsing presence in Realtime Database\n\nFirst, consider how a traditional presence system works in Realtime Database. \n\nWeb \n\n```javascript\n// Fetch the current user's ID from Firebase Authentication.\nvar uid = firebase.auth().currentUser.uid;\n\n// Create a reference to this user's specific status node.\n// This is where we will store data about being online/offline.\nvar userStatusDatabaseRef = firebase.database().ref('/status/' + uid);\n\n// We'll create two constants which we will write to \n// the Realtime database when this device is offline\n// or online.\nvar isOfflineForDatabase = {\n state: 'offline',\n last_changed: firebase.database.ServerValue.TIMESTAMP,\n};\n\nvar isOnlineForDatabase = {\n state: 'online',\n last_changed: firebase.database.ServerValue.TIMESTAMP,\n};\n\n// Create a reference to the special '.info/connected' path in \n// Realtime Database. This path returns `true` when connected\n// and `false` when disconnected.\nfirebase.database().ref('.info/connected').on('value', function(snapshot) {\n // If we're not currently connected, don't do anything.\n if (snapshot.val() == false) {\n return;\n };\n\n // If we are currently connected, then use the 'onDisconnect()' \n // method to add a set which will only trigger once this \n // client has disconnected by closing the app, \n // losing internet, or any other means.\n userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function() {\n // The promise returned from .onDisconnect().set() will\n // resolve as soon as the server acknowledges the onDisconnect() \n // request, NOT once we've actually disconnected:\n // https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect\n\n // We can now safely set ourselves as 'online' knowing that the\n // server will mark us as offline once we lose connection.\n userStatusDatabaseRef.set(isOnlineForDatabase);\n });\n});https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node-1st-gen/presence-firestore/public/index.js#L19-L62\n```\n\nThis example is a complete Realtime Database presence system. It handles\nmultiple disconnections, crashes and so on.\n\nConnecting to Cloud Firestore\n\nTo implement a similar solution in Cloud Firestore use the same\nRealtime Database code, then use Cloud Functions to keep Realtime Database and\nCloud Firestore in sync.\n\nIf you haven't already, add [Realtime Database](https://firebase.google.com/docs/database/) to your project\nand include the above presence solution.\n\nNext you'll synchronize the presence state to Cloud Firestore through\nthe following methods:\n\n1. Locally, to the offline device's Cloud Firestore cache so that the app knows it's offline.\n2. Globally, using a Cloud Function so that all other devices accessing Cloud Firestore know this specific device is offline.\n\n| **Note:** Remember that whenever you lose internet connectivity, you have no way to synchronize data, so you must write the same data to the same location, as shown in the following examples. This is necessary to ensure all devices receive the change in online status.\n\nUpdating Cloud Firestore's local cache\n\nLet's take a look at the changes required to fulfill the first issue - updating\nCloud Firestore's local cache. \n\nWeb \n\n```javascript\n// ...\nvar userStatusFirestoreRef = firebase.firestore().doc('/status/' + uid);\n\n// Firestore uses a different server timestamp value, so we'll \n// create two more constants for Firestore state.\nvar isOfflineForFirestore = {\n state: 'offline',\n last_changed: firebase.firestore.FieldValue.serverTimestamp(),\n};\n\nvar isOnlineForFirestore = {\n state: 'online',\n last_changed: firebase.firestore.FieldValue.serverTimestamp(),\n};\n\nfirebase.database().ref('.info/connected').on('value', function(snapshot) {\n if (snapshot.val() == false) {\n // Instead of simply returning, we'll also set Firestore's state\n // to 'offline'. This ensures that our Firestore cache is aware\n // of the switch to 'offline.'\n userStatusFirestoreRef.set(isOfflineForFirestore);\n return;\n };\n\n userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function() {\n userStatusDatabaseRef.set(isOnlineForDatabase);\n\n // We'll also add Firestore set here for when we come online.\n userStatusFirestoreRef.set(isOnlineForFirestore);\n });\n});https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node-1st-gen/presence-firestore/public/index.js#L68-L112\n```\n\nWith these changes we've now ensured that the *local* Cloud Firestore state will always\nreflect the online/offline status of the device. This means you can listen to the\n`/status/{uid}` document and use the data to change your UI to reflect connection\nstatus. \n\nWeb \n\n```javascript\nuserStatusFirestoreRef.onSnapshot(function(doc) {\n var isOnline = doc.data().state == 'online';\n // ... use isOnline\n});https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node-1st-gen/presence-firestore/public/index.js#L118-L121\n```\n\nUpdating Cloud Firestore globally\n\nAlthough our application correctly reports online presence to itself, this status\nwill not be accurate in other Cloud Firestore apps yet because our \"offline\"\nstatus write is local only and won't be synced up when a connection is restored. To counter\nthis, we'll use a Cloud Function which watches the `status/{uid}` path in Realtime\nDatabase. When the Realtime Database value changes the value will sync to Cloud Firestore\nso that all users' statuses are correct. \n\nNode.js \n\n```javascript\nfirebase.firestore().collection('status')\n .where('state', '==', 'online')\n .onSnapshot(function(snapshot) {\n snapshot.docChanges().forEach(function(change) {\n if (change.type === 'added') {\n var msg = 'User ' + change.doc.id + ' is online.';\n console.log(msg);\n // ...\n }\n if (change.type === 'removed') {\n var msg = 'User ' + change.doc.id + ' is offline.';\n console.log(msg);\n // ...\n }\n });\n });https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node-1st-gen/presence-firestore/public/index.js#L128-L147\n```\n\nOnce you deploy this function, you'll have a complete presence system running\nwith Cloud Firestore. Below is an example of monitoring for any users who\ncome online or go offline using a `where()` query. \n\nWeb \n\n```javascript\nfirebase.firestore().collection('status')\n .where('state', '==', 'online')\n .onSnapshot(function(snapshot) {\n snapshot.docChanges().forEach(function(change) {\n if (change.type === 'added') {\n var msg = 'User ' + change.doc.id + ' is online.';\n console.log(msg);\n // ...\n }\n if (change.type === 'removed') {\n var msg = 'User ' + change.doc.id + ' is offline.';\n console.log(msg);\n // ...\n }\n });\n });https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node-1st-gen/presence-firestore/public/index.js#L128-L147\n```\n\nLimitations\n\nUsing Realtime Database to add presence to your Cloud Firestore app is\nscalable and effective but has some limitations:\n\n- **Debouncing** - when listening to realtime changes in Cloud Firestore, this solution is likely to trigger multiple changes. If these changes trigger more events than you want, manually debounce the Cloud Firestore events.\n- **Connectivity** - this implementation measures connectivity to Realtime Database, not to Cloud Firestore. If the connection status to each database is not the same, this solution might report an incorrect presence state.\n- **Android** - on Android, the Realtime Database disconnects from the backend after 60 seconds of inactivity. Inactivity means no open listeners or pending operations. To keep the connection open, we recommended you add a value event listener to a path besides `.info/connected`. For example you could do `FirebaseDatabase.getInstance().getReference((new Date()).toString()).keepSynced()` at the start of each session. For more information, see [Detecting Connection State](https://firebase.google.com/docs/database/android/offline-capabilities#section-connection-state)."]]