每当用户打开聊天室时,我都试图添加用户的联机状态。

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(),则值会在Online中更新为last_seen,但在2-3秒后,即使用户在线聊天,它也会更改为time(unix format)
有没有更好的方法来处理这个问题?

最佳答案

您可以使用发布-订阅模式。让我们了解什么是发布-订阅模式。
publish–subscribe是一种消息传递模式,其中消息的发送者,
呼叫发布者,不要将消息直接发送到
特定的接收者,称为订阅者,但是
将消息发布到类中,而不知道
订户,如果有的话,可能有。同样,订户表示
对一个或多个类感兴趣,并且只接收
兴趣,不知道有哪些出版商,如果有的话。
来源:Wikipedia
下面是使用RabbitMQ MQTT Adapter的示例:
将用户A的应用程序订阅到主题“/topic/user-A”,将用户B的应用程序订阅到主题“/topic/user-B”,并将联机/脱机状态发布到主题“/topic/presence”。
在后端服务器上创建程序以订阅“/topic/presence”。如果有任何更新来自let,比如说用户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

真正的挑战是如何发布“离线”。一种情况是,如果用户在internet仍处于活动状态时关闭应用程序,则应用程序可以将“脱机”状态发布到服务器,但当internet停止工作时会发生什么情况?
让我们通过“最后的遗嘱和遗嘱”(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/
对于使用类似在线服务的示例源代码,您可以查看Githubhttps://github.com/AppLozic/Applozic-Android-SDK中提供的Applozic Chat SDK代码

关于ios - Firebase聊天设置用户的在线状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39688209/

10-11 22:32
查看更多