我已经为我的应用程序创建了一个消息传递系统,并且正在对聊天日志中的消息进行分页,但是我遇到的问题是,如果发送了新消息,则用户必须离开屏幕并重新打开控制器才能查看他们已发送/接收的新消息。我试图重新加载集合视图,并再次观察消息,但是没有运气。任何帮助表示赞赏。
观察消息。具有分页功能。(效果很好!在初始加载时如此)。
var messages = [Message]()
fileprivate func observeMessages() {
guard let uid = Auth.auth().currentUser?.uid else { return }
guard let userId = user?.uid else { return }
if currentKey == nil {
let userMessageRef = Database.database().reference().child("user-message").child(uid).child(userId).queryLimited(toLast: 10).observeSingleEvent(of: .value) { (snapshot) in
guard let first = snapshot.children.allObjects.first as? DataSnapshot else { return }
guard var allObjects = snapshot.children.allObjects as? [DataSnapshot] else { return }
allObjects.forEach({ (snapshot) in
let messageId = snapshot.key
let ref = Database.database().reference().child("messages").child(messageId)
ref.observe(.value, with: { (snapshot) in
guard let dict = snapshot.value as? [String: Any] else { return }
let message = Message(dictionary: dict)
self.messages.append(message)
self.messages.sort(by: { (message1, message2) -> Bool in
return message1.timeStamp.compare(message2.timeStamp) == .orderedDescending
})
self.collectionView?.reloadData()
})
})
self.currentKey = first.key
}
} else {
let userMessageRef = Database.database().reference().child("user-message").child(uid).child(userId).queryOrderedByKey().queryEnding(atValue: self.currentKey).queryLimited(toLast: 4).observeSingleEvent(of: .value) { (snapshot) in
guard let first = snapshot.children.allObjects.first as? DataSnapshot else { return }
guard var allObjects = snapshot.children.allObjects as? [DataSnapshot] else { return }
allObjects.forEach({ (snapshot) in
if snapshot.key != self.currentKey {
let messageId = snapshot.key
let ref = Database.database().reference().child("messages").child(messageId)
ref.observe(.value, with: { (snapshot) in
guard let dict = snapshot.value as? [String: Any] else { return }
let message = Message(dictionary: dict)
self.messages.append(message)
self.messages.sort(by: { (message1, message2) -> Bool in
return message1.timeStamp.compare(message2.timeStamp) == .orderedDescending
})
self.collectionView?.reloadData()
})
}
})
self.currentKey = first.key
}
}
}
答案 0 :(得分:1)
From Firebase database documentation
在某些情况下,您可能希望调用一次回调,然后立即将其删除,例如在初始化您不希望更改的UI元素时。您可以使用observeSingleEventOfType方法简化这种情况:添加的事件回调将触发一次,然后不再触发。
我建议您更改为observeEventType:withBlock
,这样您就可以观察所有更改事件。
希望这会有所帮助。
答案 1 :(得分:0)
我设置方法的方法是在viewDidLoad中调用该函数,然后在viewDidAppear中再次调用该函数。我还在学习,但是您可能想尝试一下,它可能看起来像这样:
browser = webdriver.Firefox()
url = 'http://www.google.com/'
browser.get(url)
browser.maximize_window()
再次在viewDidAppear中:
override func viewDidLoad() {
super.viewDidLoad()
observeMessages(for: userID) { (messages) in
self.messages = messages
self.collectionView.reloadData()
}
}