我有一个简单的消息应用程序,正在调用以下函数并传递发送消息的人的 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)
}
在第一次调用数据库之前,该函数一直被调用。因此,如果我将 print(uid) 放在 Firebase 调用之上,它会在调用数据库之前打印所有 uid。
用户的数据库结构: [
组的数据库结构: [
最佳答案
我认为您可以使用完成处理程序从 fetchUser
方法中获取 user
,然后创建一个字典来放置 message
和user
在一起。所以你可以这样做:
private func fetchUser(withMessage message: Message, completionHandler: @escaping (User, Message) -> ()) {
guard let messageUserId = message.fromId else {
return
}
FIRDatabase.database().reference().child("users").child(messageUserId ).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any] {
let user = User()
user.name = dictionary["name"] as? String
user.profileImageUrl = dictionary["profileImageURL"] as? String
//self.users.append(user)
completionHandler(user, message)
self.attemptReloadOfCollection()
}
}, withCancel: nil)
}
然后替换
self.fetchUser(withId: messageUserId)
与
self.fetchUser(withMessage: message) { user, message in
var dict = [String: Any]()
dict["user"] = user
dict["message"] = message
self.finalArr.append(dict)
print(self.finalArr) // to see if we have the right output
}
关于ios - Firebase 引用调用未返回正确的对象(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46722425/