swiftuicollectionviewchatjsqmessagesviewcontroller

how do I just show the profile Image next to the last message of an user in a chat


I am using JSQ Messages Controller to add a chat feature to my app, but I also managed to create one on my own with a collectionview. However Injust can‘t figure out how to show the profile picture just next to the last message of an user. For example he writes 3 messages and no one else in the chat does write anything in between. Now I just want to show only next to the third message the profile picture. When I return the items (cells) I just can edit the item I am about to return (at indexPath.item) though. I can make sure that the message before (at indexPath.item - 1) has the same senderID. But I can‘t check if the cell at indexPath.item + 1) is from the same sender. Since I am not able to check the second one, I have no clue how to solve my problem. I hope you understood what I want to do.


Solution

  • First I would like to point you to the new project that is taking over JSQMessageViewController since JSQMessageViewController is deprecated, It is called MessageKit.

    Make a function to determine if it is the last message in a set.

    //Check if it is the last message in all your messages
    //Check that the next message is not sent by the same person. 
     func isLastInSet(indexOfMessage: IndexPath) -> Bool {
         if indexOfMessage.item == messages.count -1 {
           return true
         } else if {
            return messages[indexOfMessage.item].senderID() != messages[indexOfMessage.item + 1].senderID()
         }
     }
    

    Now just add a call to isLastInSet within the avatarImageDataForItemAt if it returns a false set the image to nil

    func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {   
        if let message = messages[indexPath.item]{
          if isLastInSet(indexOfMessage: indexPath) {
             return ImageData
          }
        }
      return nil
      }