![](/img/trans.png)
[英]Firebase observer not observing database changes when called in viewDidLoad
[英]Database observer function not acting as observer in viewDidLoad, only viewDidAppear
我有一個負責觀察數據庫的功能。 它會在首次加載時設置一些詞典,然后關注后續更改並相應地更新這些詞典。 在viewDidAppear
調用時,這可以完美地工作。 但是,如果我將其移至viewDidLoad
,它將初始設置值,但不會“觀察”-換句話說,如果我更改其中一個值(例如status),則直到離開視圖並返回時該更改才會反映出來。
由於其他原因,我需要在viewDidLoad
使用它-為什么僅當它在viewDidAppear
,為什么它只能作為觀察者正常工作?我是否可以更改使其在viewDidLoad
作為觀察者工作?
這是功能:
func getParticipantInfo() {
let databaseRef = FIRDatabase.database().reference()
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 {
// Nav bar
self.navCollectionView?.collectionView?.reloadData()
}
}
}
})
}
我看到的一個原因是您僅觀察到.childAdded
事件。 您必須訂閱所有更改才能觸發事件。 嘗試訂閱.value
事件,該事件將監聽數據庫上的所有更改並反映在應用程序中。
就viewDidLoad
和viewDidAppear
而言,在將訂閱服務器附加到Firebase之前,請確保已設置所有類變量。 只要設置正確, viewDidLoad
或viewDidAppear
都無關緊要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.