Send iMessage iOS Tutorial

With the MessageUI FrameWork we can add text messaging functionality in our app. In this tutorial we will send a text message using the MFMessageComposeViewController object. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App

For product name, use iOS12SendiMessageTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard. Drag a Button to the main view. Select the button and give it a title of "Send iMessage". Select the Button and choose the "Resolve Auto Layout Button". (3rd button in the bottom-right corner) and select "Add Missing Constraints".

The Storyboard should look like this. 

Select the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl and drag from the Button to the View Controller class and create the following Action.

Our View Controller must be able to respond to updates from a message compositon, so it must conform to the MFMessageComposeViewControllerDelegate protocol. In ViewController.swift change the class declaration to

class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {

Next, implement the sendMessage method

@IBAction func sendMessage(_ sender: Any) {
    let messageVC = MFMessageComposeViewController()
        
    messageVC.body = "Enter a message";
    messageVC.recipients = ["Enter tel-nr"]
    messageVC.messageComposeDelegate = self
        
    self.present(messageVC, animated: true, completion: nil)
}

We initialize a MFMessageComposeViewController and fill in the body and recipients. Fill in your own values. Then the View Controller is presentented. The user can edit the body and change the recipients if they like, and press the send button. To conform the view controller to the MFMessageComposeViewControllerDelegate protocol, the messageComposeViewController:didFinishWithResult method is required.

func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
    switch (result) {
        case .cancelled:
            print("Message was cancelled")
            dismiss(animated: true, completion: nil)
        case .failed:
            print("Message failed")
            dismiss(animated: true, completion: nil)
        case .sent:
            print("Message was sent")
            dismiss(animated: true, completion: nil)
        default:
        break
    }
}

We check if the messaging has succeeded or not and we dismiss our view controller. Because the Simulator isn't able to send iMessages, this project should be run on a device. Build and Run the project, enter some text and send the iMessage

You can download the source code of the iOS12SendiMessageTutorial at the ioscreator repository on github.