【问题标题】:How can I update user online status without reloading the controller?如何在不重新加载控制器的情况下更新用户在线状态?
【发布时间】:2019-03-09 23:34:51
【问题描述】:

所以我制作了一个可用的聊天应用程序,其中后端是 Firestore(我知道有 Firebase。)我还有一个文档,其中用户在线离线状态是记录器。

当用户登录“isOnline”节点时,该值会更改为 true 或“online”,而当应用进入后台时,该值会更改为“offline”。

唯一的问题是我必须重新加载 viewController 才能进行更改。有什么办法可以实时更新用户状态

AppDelegate:-

在 ApplicationDidBecomeActive 中

 if User.currentUser() != nil {
                updateCurrentUserInFirestore(withValues: [kISONLINE : "online"]) { (success) in
                }
            }

在 ApplicationDidEnterBackground 中

if User.currentUser() != nil {
            updateCurrentUserInFirestore(withValues: [kISONLINE : "offline"]) { (success) in

            }
        }

比chatViewController中导航栏的设置如下

userstatus func
     if withUser.isOnline == "online" {
                navigationController?.navigationBar.barTintColor = UIColor.flatGreen()
            }else{
               navigationController?.navigationBar.barTintColor = UIColor.flatBlue()
            }

下面是检查状态变化的功能

 func updateUserOnlineStatus() {

        if !isGroup! {
            var withUser = withUsers.first!


            withUserUpdateListener = reference(.User).document(withUser.isOnline).addSnapshotListener { (snapshot, error) in
                guard let snapshot = snapshot else {  return }
                if snapshot.exists {
                    print(snapshot)
                   let withUser = User(_dictionary: snapshot.data()! as NSDictionary)
                   self.setUIForSingleChat(withUser: withUser)
                }
            }

        }
    }

【问题讨论】:

  • 好吧,你可以创建一些可观察的类来通知观察对象的状态变化。然后在您的 viewController 中,您将自己添加为观察者,一旦用户登录或退出,您就会收到通知。或者,您可以使用 NSNotificationNSNotificationCenter 通知您的 viewController 发生了变化。

标签: swift firebase-realtime-database google-cloud-firestore user-presence


【解决方案1】:

这成功了,旧代码中存在一些问题

func updateUserOnlineStatus() {
    print("User update online status")
    if !isGroup! {
        var withUser = withUsers.first!
        withUserUpdateListener = reference(.User).document(withUser.objectId).addSnapshotListener { (snapshot, error) in
            if error != nil {
               print("error")
            }
            print("update user status")
            let withUser = FUser(_dictionary: snapshot!.data()! as NSDictionary)
            if withUser.isOnline == "online" {
                self.navigationController?.navigationBar.barTintColor = UIColor.flatGreen()
            }else{
               self.navigationController?.navigationBar.barTintColor = UIColor.flatBlue()
            }


            }

        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-28
    • 2012-08-09
    • 1970-01-01
    • 2021-01-10
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    相关资源
    最近更新 更多