Search code examples
iosswiftdatechatjsqmessagesviewcontroller

How to show message date in JSQMessagesViewController


I am trying to make a chat app and I am using JSQMessagesViewController library. My Chat View show all the messages with their date and time but I am facing some little bit of problem with this library. My problem is I wanna show message date only Once. Suppose: Yesterday date contains 10 messages and today date contains 15 messages

and I wanna show Only single date of these messages as not repeat dates for every messages enter image description here


Solution

  • Well you need to determine if the message is the first of that day. Then return nil for all the others till a new day.

    I created a function to determine if my message was the first sent by that individual. It looks like this

    func firstMessageOfTheDay(indexOfMessage: NSIndexPath) -> Bool { 
      let messageDate = messages[indexOfMessage.item].date
      guard let previouseMessageDate = messages[indexOfMessage.item - 1].date else {
        return true // because there is no previous message so we need to show the date
      }
        let day = Calendar.current.component(.day, from: messageDate)
        let previouseDay = Calendar.current.component(.day, from: previouseMessageDate)
        if day == previouseDay {
            return false
        } else {
            return true
        }
    }
    

    Then call that in the appropriate function. Hope that helps let me know if you have any other questions.