首页 > 解决方案 > 如何在不重新加载控制器的情况下更新用户在线状态?

问题描述

因此,我制作了一个可用的聊天应用程序,其中后端是 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)
                }
            }

        }
    }

标签: swiftfirebase-realtime-databasegoogle-cloud-firestoreuser-presence

解决方案


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

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()
            }


            }

        }

    }

推荐阅读