我尝试设置一个函数来监听数据库某个部分内的更改:
private func observeParticipants() {
let databaseRef = FIRDatabase.database().reference()
let groupRef = databaseRef.child("groups").child(currentRoomID).child("participants")
groupRef.observe(.childAdded, with: { snapshot in
print("observe snapshot.value: \(snapshot.value)")
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)
print("\n\navatarDictionary:\n \(self.avatarDictionary)")
print("\nhandleDictionary:\n \(self.handleDictionary)")
print("\ngenderDictionary:\n \(self.genderDictionary)")
print("\nnameDictionary:\n \(self.nameDictionary)")
print("\nstatusDictionary:\n \(self.statusDictionary)")
self.navBarCollectionView.reloadData()
}
}
})
}
当我运行它时,它会加载正确的值,但如果我进行更改,例如向该组添加新用户,则它不会反映该更改。数据库更新正常,但观察者没有看到。有什么方法可以重新写这个来使观察得当吗?如果有帮助,我可以发布我的数据库结构。
谢谢!
编辑:数据库结构:
编辑:添加第二个用户后的snapshot.value:
Snapshot.value: Optional({
gender = female;
handle = sav;
name = Savina;
profilePicture = "https://graph.facebook.com/1929991317219760/picture?type=large&return_ssl_resources=1";
status = F8B016;
})
编辑2:
这是最初用于获取所有用户值的代码,也是每次离开视图并返回时的代码。它只是作为一个观察者没有正常行动,即如果我添加一个参与者,它没有看到并更新必要的值,如集合视图。我必须离开视野,然后回来让它发生。
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)
print("\n\navatarDictionary:\n \(self.avatarDictionary)")
print("\nhandleDictionary:\n \(self.handleDictionary)")
print("\ngenderDictionary:\n \(self.genderDictionary)")
print("\nnameDictionary:\n \(self.nameDictionary)")
print("\nstatusDictionary:\n \(self.statusDictionary)")
self.navBarCollectionView.reloadData()
}
}
})
}