如果对话已经开始,那么我将使用缓存中的最后一条消息(例如self.fetchMessages(startingAt: lastMessageID!)
)从firebase中获取消息。此功能与获取所有消息基本相同,除了它从某个点开始获取,例如:
func fetchMessages(startingAt:String) {
if started == true {
print(startingAt)
let messageRef = Database.database().reference().child("messages").child(convoID!).queryOrderedByKey().queryStarting(atValue: startingAt)
messageRef.observe(.childAdded) { (snapshot) in
if let value = snapshot.value as? NSDictionary {
print(value)
let newMessage = message()
newMessage.messageText = value["content"] as? String
newMessage.sender = value["sender"] as? String
newMessage.messageID = snapshot.key
newMessage.messageTime = value["time"] as? Int
if snapshot.key == startingAt {
print("firstItem")
}
else {
self.messageList.append(newMessage)
self.messagesTableView.reloadData()
self.scrollToBottom()
self.addMessageToCache(messageToCache: newMessage)
}
self.queryingStatus = true
}
}
}
}
似乎正在从Firebase中进行多个观察,就像正在添加多个观察者一样。例如,当我添加一条消息时,控制台日志将显示:
{
content = 0;
sender = CAD54A563CAB99107D9BBDB7F2234FA3;
time = 1532629519121;
}
adding
{
content = 0;
sender = CAD54A563CAB99107D9BBDB7F2234FA3;
time = 1532629519121;
}
adding
{
content = 0;
sender = CAD54A563CAB99107D9BBDB7F2234FA3;
time = 1532629519121;
}
adding
{
content = 0;
sender = CAD54A563CAB99107D9BBDB7F2234FA3;
time = 1532629519121;
}
adding
{
content = 0;
sender = CAD54A563CAB99107D9BBDB7F2234FA3;
time = 1532629519121;
}
adding
{
content = 0;
sender = CAD54A563CAB99107D9BBDB7F2234FA3;
time = 1532629519121;
}
adding
{
content = 0;
sender = CAD54A563CAB99107D9BBDB7F2234FA3;
time = 1532629519121;
}
每次打开屏幕时,它都会增加。例如,第一条消息不会重复,我发送的第二条消息也会重复,如果我重新打开屏幕并发送第三条消息,它将在快照中出现三次...好像正在添加多个观察者? / p>
答案 0 :(得分:0)
从本质上讲,存在一些问题。首先,需要删除的观察者确实消失了。第二,正在从缓存中删除对话,因为删除对话的功能是在convos数组完全加载之前调用的。