iMessage app won't insert message into active conversation

980 views Asked by At

I'm having an issue with a Message Extension app I'm trying to create. Whenever I try to insert text into a conversation nothing happens. This is what I'm using:

import UIKit
import Messages

class MessagesViewController: MSMessagesAppViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let sendButton = UIButton(type: UIButtonType.custom)
        sendButton.frame = CGRect(x: view.frame.midX, y: view.frame.midY, width: 100, height: 50)
        sendButton.setTitle("Send", for: UIControlState.normal)
        sendButton.addTarget(self, action: #selector(sendButtonTapped(sender:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(sendButton)

}



     func sendButtonTapped(sender: UIButton!){

         let layout = MSMessageTemplateLayout()
         layout.caption = "My Survey"
         layout.image = UIImage(named: "myImage")

         let message = MSMessage()
         message.layout = layout

         self.activeConversation?.insert(message, completionHandler: nil)

    }
}

Whenever I run it using this code nothing happens. The weird part is that if I change self.activeConversation? to self.activeConversation! the app crashes. I don't understand why this is happening because I'm in a conversation and my app has loaded.

1

There are 1 answers

1
MK_iOS On

Can you try this.

func sendButtonTapped(sender: UIButton!) {

guard let conversation = activeConversation else { fatalError("Expected a  conversation") }

        let session = conversation.selectedMessage?.session ?? MSSession()

        let message = MSMessage(session: session)

        let layout = MSMessageTemplateLayout()
        layout.image = createImageForMessage(value: GlobalData.sharedManager.cardUrl)
        layout.caption = "Caption"
        layout.imageTitle = GlobalData.sharedManager.cardTitle
        layout.imageSubtitle = "Image subtitle"
        layout.trailingCaption = "Trailing caption"
        layout.subcaption = "Subcaption"
        layout.trailingSubcaption = "Trailing subcaption"
        message.layout = layout

        conversation.insert(message) {error in
                  // empty for now
              }
}}