iosswiftuiimessage-extension

Creating an iMessage app without using a storyboard


I would like to create an iMessage app without using a storyboard, and preferably using SwiftUI for the view. I am following an answer in an Apple forum, but I am not getting a view inside the iMessage window.

I changed my Info.plist to:

<key>NSExtension</key>
    <dict>
        <key>NSExtensionPointIdentifier</key>
        <string>com.apple.message-payload-provider</string>
        <key>NSExtensionPrincipalClass</key>
        <string>MessagesViewController.swift</string>
    </dict>

A simple view controller:

import Messages
import SwiftUI

@objc (MessagesViewController)
class MessagesViewController: MSMessagesAppViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let child = UIHostingController(rootView: SwiftUIView())
        child.view.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(child.view)
        
        NSLayoutConstraint.activate([
            child.view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0),
            child.view.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0),
            child.view.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0),
            child.view.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0)
            ])
    }

And finally a simple SwiftUI view:

struct SwiftUIView: View {
    var body: some View {
        Text("Hello, Earth!")
    }
}

So far, no luck. Does anyone have an idea where I've gone wrong?


Solution

  • Your problem is in your Info.plist file. You have specified MessagesViewController.swift as the NSExtensionPrincipalClass

    This is the source file name, not the class name. You need to specify the class name (which is MessagesViewController) prefixed with your module name.

    Change your Info.plist to

    <key>NSExtension</key>
        <dict>
            <key>NSExtensionPointIdentifier</key>
            <string>com.apple.message-payload-provider</string>
            <key>NSExtensionPrincipalClass</key>
            <string>$(PRODUCT_MODULE_NAME).MessagesViewController</string>
        </dict>