我有一个用户到用户的应用程序。如果用户失去互联网连接,我希望 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/