Search code examples
iosswiftmsmessage

How to make an iMessage app that only shows the current message?


I am making a iMessage game. I want only the current iMessage session to show and all of the previous ones to be minimized. For a turn based game I don't want users to go back and see all the previous moves.

How might this be done with iOS 10 and Swift?


Solution

  • You want to use a single MSSession across all the messages in the conversation.

    1. The session variable (declared in the main class)

    class MessagesViewController: MSMessagesAppViewController {
        var session: MSSession?
    
        ...
    }
    

    2. Setting the session (when the app becomes active)

    override func willBecomeActive(with conversation: MSConversation) {
        if let selected = conversation.selectedMessage {
            session = selected.session
        }
    }
    

    3. Use the session (when building the MSMessage)

    if session == nil {
        session = MSSession()
    }
    
    let message = MSMessage(session: session!)
    

    Full Code Example

    class MessagesViewController: MSMessagesAppViewController {
        var session: MSSession?
    
        override func willBecomeActive(with conversation: MSConversation) {
            if let selected = conversation.selectedMessage {
                session = selected.session
            }
        }
    
        func buildMessage() {
            if session == nil {
                session = MSSession()
            }
    
            let message = MSMessage(session: session!)
    
            ...
        }
    }