我有一个用户到用户应用。如果用户丢失了互联网连接,我希望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")
})
答案 0 :(得分:2)
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。它根据网络可用性返回true / false。
checkNetworkStatus(uid) {
let userRef = this.rootRef.child('/presence/' + uid);
return userRef.on('value', function (snapshot) {
return snapshot.val();
});
}