ios - Firebase 引用调用未返回正确的对象(Swift)

标签 ios swift firebase firebase-realtime-database

我有一个简单的消息应用程序,正在调用以下函数并传递发送消息的人的 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。

用户的数据库结构: ["database structure users"]

组的数据库结构: ["database structure groups"]

最佳答案

我认为您可以使用完成处理程序从 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


}

关于ios - Firebase 引用调用未返回正确的对象(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46722425/

相关文章:

ios - 我怎样才能同时使用带有导航 Controller 的 segue?

ios - 我的 firebase int 返回 nil

android - 无法从包外部访问电话验证卡

ios - 如何在 Xcode 8 中使用 Swift 3 创建 managedObjectContext?

ios - 匹配 'transparent' 导航栏的颜色

ios - 以编程方式自动布局不起作用

swift - 如何解决Xcode 8.3 beta中的 "String interpolation produces a debug description for an optional value; did you mean to make this explicit?"?

即使在四天之后 Firebase 也不会与 BigQuery 同步事件

c# - PushSharp - 如何触发 OnDeviceSubscriptionExpired

ios - 带有 UIButton 的自定义 UITableView 单元不调用 didSelectRowAtIndexPath