在viewDidLoad中调用时,Firebase观察者不会观察数据库更改

时间:2017-05-27 17:51:03

标签: ios swift firebase firebase-realtime-database

我有一个函数,我想充当用户值的观察者,以及在呈现视图时设置一些初始值。

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中的变化?

1 个答案:

答案 0 :(得分:0)

我现在不知道为什么,但这解决了我的问题。我所要做的就是将.childAdded更改为.value,一切都按照我的预期开始工作。我知道这可能不是最好的做法,但它只是解决问题的简单方法。