Как отобразить имя учетной записи Firebase пользователей с помощью JSQMessages? - PullRequest
0 голосов
/ 28 декабря 2018

Я пытаюсь получить информацию о пользователях, такую ​​как, имя и фамилию, из базы данных Firebase и отобразить ее над всплывающим окном сообщения, когда пользователь отправляет сообщение другому пользователю.

Ниже мой код.Я могу отправлять сообщения, это просто отображает имя пользователя firebase.Есть предложения?

Спасибо!

class ChatViewController: JSQMessagesViewController {

var messages = [JSQMessage] ()

lazy var outgoingBubble: JSQMessagesBubbleImage = {
    return JSQMessagesBubbleImageFactory()!.incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleLightGray())
} ()

lazy var incomingBubble: JSQMessagesBubbleImage = {
    return JSQMessagesBubbleImageFactory()!.incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleBlue())
} ()

override func viewDidLoad() {
    super.viewDidLoad()

    self.senderDisplayName = "Wolverine"
    self.senderId = Auth.auth().currentUser?.uid


    // The first line hides the attachment button on the left of the chat text input field. The other two lines of code set the avatar size to zero, again, hiding it.

    inputToolbar.contentView.leftBarButtonItem = nil
    collectionView.collectionViewLayout.incomingAvatarViewSize = CGSize.zero
    collectionView.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero

    // Do any additional setup after loading the view.
    let query = Constants.refs.databaseChats.queryLimited(toLast: 10)

    _ = query.observe(.childAdded, with: { [weak self] snapshot in

        if  let data        = snapshot.value as? [String: String],
            let id          = data["sender_id"],
            let name        = data["name"],
            let text        = data["text"],
            !text.isEmpty
        {
            if let message = JSQMessage(senderId: id, displayName: name, text: text)
            {
                self?.messages.append(message)

                self?.finishReceivingMessage()
            }
        }
    })
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
    return messages[indexPath.item]

}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return messages.count
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource!
{
    return messages[indexPath.item].senderId == senderId ? outgoingBubble : incomingBubble
}

// This function simply returns nil when JSQMVC wants avatar image data, effectively hiding the avatars. hides the avatars for message bubbles. JSQMVC can show them, but its not needed.

override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource!
{
    return nil
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString!
{
    return messages[indexPath.item].senderId == senderId ? nil : NSAttributedString(string: messages[indexPath.item].senderDisplayName)
}

override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAt indexPath: IndexPath!) -> CGFloat
{
    return messages[indexPath.item].senderId == senderId ? 0 : 15
}
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!)
{
    let ref = Constants.refs.databaseChats.childByAutoId()

    let message = ["sender_id": senderId, "name": senderDisplayName, "text": text]

    ref.setValue(message)

    finishSendingMessage()
  }
 }
...