无法访问 Firebase 子项

Can't access Firebase child

我有一个 firebase 数据库参考

FIRDatabase.database().reference().child("messages").child("\(self.convoId!)").childByAutoId()

我想在 DisplayViewController 中从我的 firebase 数据库访问 ReceiverName,但是当我调用数据库引用时,由于 convoId 而出现错误。这就是 convoId 的声明方式(在 MessagesViewController 中)。

 override func viewDidLoad() {
        super.viewDidLoad()
  let receiverId = receiverData as! String
        let receiverIdFive = String(receiverId.characters.prefix(5))
        let senderIdFive = String(senderId.characters.prefix(5))
        if (senderIdFive > receiverIdFive)
        {
            self.convoId = senderIdFive + receiverIdFive
        }
        else
        {
            self.convoId = receiverIdFive + senderIdFive
}
    }

receiverData 是从 UserviewController 传递给 MessagesViewController,"senderId" 是唯一标识当前用户发送消息的字符串标识符,在 JSQMessagesViewController.h 中自动声明。所以基本上,我不能在我的 DisplayViewController 中重新声明 convoId。但是,在 DisplayViewController 中,我需要访问 ReceiverName。

这就是我尝试检索 ReceiverName 的方式:

let rootRef = FIRDatabase.database().reference()        
rootRef.child("messages").observeSingleEvent(of: .value) { 
    (snapshot: FIRDataSnapshot) in
    let loggedInUserData = snapshot
    if let postsDictionary = snapshot .value as? [String: AnyObject] {
        for post in postsDictionary {
            self.messages.add(post.value)
        }
        self.MessageTableView.reloadData()
    }
}

然后我将派生数据填充到 tableviewcell 中:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! MessageTableViewCell


    //Configure the cell


    print(messages[indexPath.row])
    let message = self.messages[indexPath.row] as! [String: AnyObject]
    cell.SellerName.text = message["ReceiverName"] as? String

       return cell
}

在你的 observeSingleEvent 函数中试试这个:

...
for post in postsDictionary {
    let messages = post.value as! [String: AnyObject]
    for (id, value) in messages {
        let info = value as! [String: AnyObject]
        let receiver = info["ReceiverName"]!
        print("\(id): \(receiver)")
        self.messages.add(value)
    }
}
...