ios - 没有互联网时 Swift Firebase ondisconnect Action

标签 ios swift firebase firebase-realtime-database

我有一个用户到用户的应用程序。如果用户失去互联网连接,我希望 firebase 查询“isUserLogon:false”。我使用 ondisconnect 这在用户终止应用程序时正常工作,但在他们与互联网断开连接时则不然。最好的解决办法是什么。我假设因为没有连接 firebase 无法更新。如果用户与互联网断开连接,我不希望 firebase 认为他们在不活动时仍处于事件状态,其他应用程序如何处理这种情况。

let path = "rquest/frontEnd/users/\(self.currentUserId()!)"

        let myConnectionsRef = FIRDatabase.database().reference(withPath: path).child("isUserLogon")


        let lastOnlineRef = FIRDatabase.database().reference(withPath: path).child("lastOnline")

        let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")

        connectedRef.observe(.value, with: { snapshot in
            // only handle connection established (or I've reconnected after a loss of connection)
            guard let connected = snapshot.value as? Bool, connected else { return }

            // add this device to my connections list
            // this value could contain info about the device or a timestamp instead of just true
            let con = myConnectionsRef
            con.setValue(true)

            // when this device disconnects, remove it
            con.onDisconnectSetValue(false)

            // when I disconnect, update the last time I was seen online
            lastOnlineRef.onDisconnectSetValue("Date here")
        })

最佳答案

This article解释了如何在 firebase 中构建状态系统以维护在线/离线状态。

设置基本状态系统的基本步骤:

var amOnline = new Firebase('https://<demo>.firebaseio.com/.info/connected');
var userRef = new Firebase('https://<demo>.firebaseio.com/presence/' + userid);
amOnline.on('value', function(snapshot) {
  if (snapshot.val()) {
    userRef.onDisconnect().remove();
    userRef.set(true);
  }
});

就是这样!现在只需调用下面的函数传递你想知道网络状态的用户的 uid。它根据网络可用性返回真/假。

 checkNetworkStatus(uid) {
        let userRef = this.rootRef.child('/presence/' + uid);
        return userRef.on('value', function (snapshot) {
            return snapshot.val();
        });
 }

关于ios - 没有互联网时 Swift Firebase ondisconnect Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44044965/

相关文章:

swift - 使用自定义解码器解码 Firestore 结构时获取 DocumentID

ios - Appium iOS Safari 打开新标签,接受提醒并在两个标签之间切换

swift - 为什么我的数据没有使用闭包在 View Controller 之间传递?

ios - 如何使从 Firebase 数据库检索的值作为 Swift 中的变量?

ios - 在从初始化器 swift 返回之前,在所有路径上调用 'Super.init isn' t 时出现问题。

arrays - Swift 错误 - 对成员 'subscript' 的引用不明确

android - 无法将 POJO 写入 Firebase 数据库

ios - Firebase 多个观察者复制单元格

iphone - UITableView 单元格提供错误信息

objective-c - 核心动画隐式动画不会为新添加的子层触发