IOS App中的JSQMessageView控制器

时间:2017-11-02 09:18:44

标签: ios objective-c jsqmessagesviewcontroller

我在我的应用中使用JSQMessages View Controller第三方库进行firebase聊天。如下面的一些视频和文档,我已经在我的类中使用了所有委托和数据源方法,并将我的子类命名为JSQMessagesViewController。但是当我点击发送按钮时,我重新加载集合视图以在集合视图中显示消息,但它们没有显示消息。当我点击发送按钮时,它会向firebase数据库发送消息,但不会在集合视图中显示我上面的消息。我也评论了按钮方法,并使用断点,但没有任何工作。如何在集合视图中显示上面的发送消息。我的代码就是这个,

import UIKit
import Firebase
import FirebaseDatabase
class ChatViewViewController: JSQMessagesViewController {
private var messages = [JSQMessage]()
override func viewDidLoad() {
    super.viewDidLoad()
self.senderId = "1"
    senderDisplayName="Hamza"
collectionView.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return messages.count
}
 override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
    return messages[indexPath.item]
}
 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
 return cell
}
 override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
    return nil
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
let bubbleFactory = JSQMessagesBubbleImageFactory();

    return bubbleFactory?.outgoingMessagesBubbleImage(with:UIColor.blue);
}
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
    messages.append(JSQMessage (senderId: senderId, displayName: senderDisplayName, text: text))
    print("Helllo")
    collectionView.reloadData()

    finishSendingMessage()
}

1 个答案:

答案 0 :(得分:0)

使用此功能显示信息。

 private func observeMessages() {
 messageRef = channelRef!.child("messages")
 // 1.
let messageQuery = messageRef.queryLimited(toLast:25)

// 2. We can use the observe method to listen for new
// messages being written to the Firebase DB
 newMessageRefHandle = messageQuery.observe(.childAdded, with: { 
  (snapshot) -> Void in
  // 3
  let messageData = snapshot.value as! Dictionary<String, String>

  if let id = messageData["senderId"] as String!, let name = 
  messageData["senderName"] as String!, let text = 
  messageData["text"] as String!, text.characters.count > 0 {
 // 4
 self.addMessage(withId: id, name: name, text: text)

 // 5
 self.finishReceivingMessage()
 } else {
 print("Error! Could not decode message data")
}
})
}

接下来,在viewDidLoad()中调用您的新方法:

observeMessages()