iMessage应用程序不会将消息插入到活动对话中

时间:2016-12-30 16:52:10

标签: swift swift3 imessage imessage-extension

我在尝试创建消息扩展应用时遇到问题。每当我尝试在对话中插入文本时都没有任何反应。这就是我正在使用的:

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)

    }
}

每当我使用此代码运行它时都没有任何反应。奇怪的是,如果我将self.activeConversation?更改为self.activeConversation!,应用程序崩溃了。我不明白为什么会这样,因为我正在进行对话并且我的应用已加载。

1 个答案:

答案 0 :(得分:0)

你能试试吗?

func sendButtonTapped(发件人: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
              }
}}