每当用户打开聊天时,我都试图添加用户的在线状态。
public static func getFirebaseOnlineStatus(userRef: String) -> FIRDatabaseReference{
return FIRDatabase.database().reference()
.child("meta")
.child(userRef)
.child("last_seen")
}在ChatVC中
private func userIsOnline() {
// Firebase make this user online
firebaseLastSeen = Constants.getFirebaseOnlineStatus(SMBUser.getCurrentUser().getId())
firebaseLastSeen.setValue("Online")
}
private func observerUserOnline(){
firebaseLastSeen.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.userIsOnline()
}, withCancelBlock: { error in
print(error.description)
})
}这个逻辑对我来说似乎很糟糕,因为每次值发生变化时,我都会再次将值更改为Online,因为如果删除observerUserOnline(),则在last_seen中将值更新为Online,但在2-3秒之后,即使用户在线聊天,也会更改为time(unix format)。
有没有更好的方法来解决这个问题?
发布于 2016-09-26 13:01:21
您可以使用发布订阅模式。让我们了解什么是发布-订阅模式。
发布-订阅是一种消息传递模式,在这种模式中,消息发送者(称为发布者)不对要直接发送给特定接收者(称为订阅者)的消息进行编程,而是在不知道可能存在哪些订阅者的情况下将已发布的消息定性为类。类似地,订阅者表示对一个或多个类感兴趣,并且只接收感兴趣的消息,而不知道有哪些发布者(如果有的话)。
来源:维基百科
下面是一个使用RabbitMQ MQTT适配器的示例
订阅用户A的应用程序到一个主题“/ topic / user -a”,用户B的应用订阅到主题“/ topic / user -b”,并将在线/离线状态发布到一个主题"/ topic /presence“。在后端服务器上创建一个程序来订阅"/topic/presence“。如果任何更新来自用户A,那么将更新发布给用户A。这样,用户B将收到用户A的在线/离线更新。
User A User B PresenceListener
Subscribe /topic/user-a /topic/presence /topic/presence
Publish /topic/user-b /topic/presence friend list这里真正的挑战是如何发布“离线”。一种情况是,如果用户在互联网仍然活跃的情况下关闭应用程序,那么应用程序可以向服务器发布“脱机”状态,但是当互联网停止工作时会发生什么呢?
让我们通过“最后的遗嘱和遗嘱”(lwt)。
LWT messages are not really concerned about detecting whether a client has gone offline or not (that task is handled by keepAlive messages). LWT messages are about what happens after the client has gone offline.可以利用LWT消息来定义由代理代表客户端发布的消息,因为客户机是脱机的,不能再发布了。
来源:http://tuanpm.net/what-is-mqtt/
对于类似于存在服务的示例源代码,您可以查看我们的Applozic聊天SDK代码,这些代码可以在Github https://github.com/AppLozic/Applozic-Android-SDK中使用。
https://stackoverflow.com/questions/39688209
复制相似问题