繁体   English   中英

在ViewDidLoad中调用时,Firebase观察器无法观察数据库更改

[英]Firebase observer not observing database changes when called in viewDidLoad

我有一个函数,希望充当用户值的观察者,并在显示视图时设置一些初始值。

func getParticipantInfo() {
    let groupRef = databaseRef.child("groups").child(currentRoomIdGlobal)
    groupRef.observe(.childAdded, with: { snapshot in
        if let snapDict = snapshot.value as? [String : AnyObject] {
            for each in snapDict {
                let uid  = each.key
                let avatar = each.value["profilePicture"] as! String
                let gender = each.value["gender"] as! String
                let handle = each.value["handle"] as! String
                let name = each.value["name"] as! String
                let status = each.value["status"] as! String

                // Set those to the dictionaries [UID : value]
                self.avatarDictionary.setValue(avatar, forKey: uid)
                self.nameDictionary.setValue(name, forKey: uid)
                self.genderDictionary.setValue(gender, forKey: uid)
                self.handleDictionary.setValue(handle, forKey: uid)
                self.statusDictionary.setValue(status, forKey: uid)
                DispatchQueue.main.async {
                    self.createAvatar(senderId: uid, senderDisplayName: name, photoUrl: avatar,  color: UIColor.lightGray)
                    self.navCollectionView?.collectionView?.reloadData()
                }
            }
        }
    })
}

如果我在viewDidAppear调用此方法,则效果很好。 它从数据库中获取用户信息,设置字典,一切正常。 最重要的是,如果将新用户添加到聊天室(就像聊天室)中,该功能将更新字典以包括该新用户的值。

但是,我需要在viewDidLoad调用它,而不是在viewDidAppear调用它。 当我这样做时,它可以设置初始值,但是当有人添加到房间中时,直到我离开视图并再次返回时,这才反映在应用程序中,因此它不会“观察”它的显示方式viewDidAppear

为什么突然在viewDidLoad中调用它使它无法正常观察? 如何使其以viewDidAppear的方式实时反映更改?

我现在不知道为什么,但这为我解决了问题。 我要做的就是将.childAdded.value ,一切开始按我期望的那样工作。 我知道这可能不是最佳做法,但这是解决问题的简单方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM