【问题标题】:Firebase reference call not returning proper object (Swift)Firebase 引用调用未返回正确的对象(Swift)
【发布时间】: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


【解决方案1】:

我认为您可以使用完成处理程序从fetchUser 方法中获取user,然后制作一个字典将messageuser 放在一起。所以你可以这样做:

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


}

【讨论】:

  • @connorvo print(self.finalArr) 数组的输出是什么?
  • 用户现在与正确的消息相关联,但是它们以错误的顺序附加到数组中(仍然将所有第一个用户添加到首先发布的消息,然后是第二个用户发布,等等上)。我想我可以尝试按消息时间对数组进行排序?
  • @connorvo 如果您的要求是拥有最新消息,那么是的,您可以根据时间戳对数组进行排序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 2021-11-11
相关资源
最近更新 更多