MessageUI, SwiftUI and UIKit integration

If you want to use MFMailComposeViewController or MFMessageComposeViewController, it looks painful. But, with these tips, it’s painless. 😃

Florent Morin
2 min readJun 30, 2019

What is MessageUI?

MessageUI is a system framework that comes with iOS 3.0 to integrate external user interfaces in a UIKit environment.

With MessageUI, you can send mails using MFMailComposeViewController and messages using MFMessageComposeViewController.

And each one has a delegate for action with result.

It was designed for Objective-C and UIKit. Now, it works fine with Swift + UIKit. What about SwiftUI?

SwiftUI and UIKit

SwiftUI can work with UIKit to reuse your existing views and view controllers. UIHostingController is used for that. (or NSHostingController for macOS)

In fact, each time you are displaying a SwiftUI view, it’s embedded in a UIHostingController provided by UIKit. Today, it works like this.

So, you have a UIKit hierarchy in each SwiftUI app. Perhaps with only one UIViewController (the root UIHostingController) but it’s a UIKit hierarchy.

Your UIKit view and controller can be transformed into SwiftUI views by using UIViewRepresentableContext and UIViewControllerRepresentableContext. It’s very helpful for migration of code.

External UIKit components

External UIKit components, like MessageUI, are controlled by the OS. The OS uses UIKit today. And interacts with your app on the UIKit stack.

So, you need to use UIKit too.

How to access root view controller from SwiftUI ?

A simple line of code can be used for that.

This is a helper to get top most view controller.

SwiftUI and MessageUI

You can use MessageUI easily with SwiftUI by calling MessageUI from root view controller.

The gist

The sample source code

You can use this sample source code available on GitHub.

Any question?

You can contact me on :

--

--