Skip to content

Instantly share code, notes, and snippets.

@NeilsUltimateLab
Last active March 10, 2020 07:27
Show Gist options
  • Save NeilsUltimateLab/6df160baab1e271694a375e589242b67 to your computer and use it in GitHub Desktop.
Save NeilsUltimateLab/6df160baab1e271694a375e589242b67 to your computer and use it in GitHub Desktop.
import UIKit
import MessageUI
struct MailInfo {
var recipient: String
var subject: String?
var message: String?
var isHTML: Bool = false
}
protocol MailComposable: UIViewController {
var mailInfo: MailInfo { get }
}
extension MailComposable where Self: UIViewController {
func openMailApp() {
let email = "mailto:\(mailInfo.recipient)"
guard let url = URL(string: email) else { return }
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
extension MailComposable where Self: UIViewController & MFMailComposeViewControllerDelegate & UINavigationControllerDelegate {
func compose() {
guard MFMailComposeViewController.canSendMail() else { openMailApp(); return }
let mailComposorVC = MFMailComposeViewController()
mailComposorVC.setToRecipients([mailInfo.recipient])
if let subject = mailInfo.subject {
mailComposorVC.setSubject(subject)
}
if let message = mailInfo.message {
mailComposorVC.setMessageBody(message, isHTML: mailInfo.isHTML)
}
mailComposorVC.delegate = self
self.present(mailComposorVC, animated: true, completion: nil)
}
}
@NeilsUltimateLab
Copy link
Author

Usage

class ContactUsViewController: UIViewController, MailComposable {
    var mailInfo: MailInfo {
           MailInfo(recipient: "info@emailaddress.com")
    }

    func contactsUsAction() {
          self.compose()
    }
}

extension ContactUsViewController: MFMailComposeViewControllerDelegate, UINavigationControllerDelegate {
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error? {
        //.. all the action you need to perform after.
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment