【发布时间】:2017-10-13 04:14:05
【问题描述】:
我有一个简单的消息传递应用程序,正在调用以下函数并传递发送消息的人的 uid。每次调用函数时都会发送正确的 uid,但用户不是与该 uid 相关的用户。相反,它返回第一个用户该人收到消息的次数,然后返回下一个用户该人收到消息的次数。
例如,如果我在聊天中有两个用户(Sue 和 Bob)并且 Sue 在此聊天中总共有 10 条消息,而 Bob 有 7 条消息,它将返回 Sue 作为前 10 条消息的用户,然后将 Bob 作为用户进入决赛 7。
private func fetchUser(withId uid: String) {
FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.name = dictionary["name"] as? String
user.profileImageUrl = dictionary["profileImageURL"] as? String
self.users.append(user)
self.attemptReloadOfCollection()
}
}, withCancel: nil)
}
调用者:
private func observeMessages() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
let groupId = groupIdFromPreviousController
let groupMessagesRef = FIRDatabase.database().reference().child("groups").child(groupId).child("messages")
groupMessagesRef.observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
let messagesRef = FIRDatabase.database().reference().child("all-messages").child(messageId)
messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let message = Message(dictionary: dictionary)
guard let messageUserId = message.fromId else {
return
}
self.fetchUser(withId: messageUserId)
self.messages.append(message)
self.attemptReloadOfCollection()
DispatchQueue.main.async {
//scroll to the last index
// let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
// self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
}
}, withCancel: nil)
}, withCancel: nil)
}
在第一次调用数据库之前,该函数一直被调用。因此,如果我在 Firebase 调用上方放置一个 print(uid),它会在调用数据库之前打印所有 uid。
用户的数据库结构: [
组的数据库结构: [
【问题讨论】:
-
请显示您的 Firebase 数据库的结构
-
你从哪里调用这个方法?你能显示那部分代码吗?
-
参考和一切都很好。它不会在传入时转到 uid,而是等到该函数被调用了它将被调用的总次数,然后调用数据库。这不允许它调用正确的参考(我认为)
-
Firebase DB 是异步的,您是否在从快照中检索所有数据时以及在填充您的 collectionView 之前使用任何排序方法?根据我的说法,您正在以正确的方式获取数据,因为找不到代码中的任何错误,您可以分享 codeFile 以检查运行时输出吗?
-
@3stud1ant3 完成
标签: ios swift firebase firebase-realtime-database