David
David

Reputation: 3348

Open mail screen in own app instead of mail app

I'm using the newest Xcode and Swift version.

I'm using the following code to initiate a screen to write an e-mail:

UIApplication.shared.open(URL(string: "mailto:[email protected]")!)

This code opens the Apple mail app, creates a new e-mail and writes [email protected] into the To: field.

Sometimes you see this "write a new e-mail" window opening as overlay in the app your initiating it from, without the Apple mail app gets opened.

How can I reach that?

Upvotes: 1

Views: 120

Answers (1)

Daniel Barden
Daniel Barden

Reputation: 1024

If you want to send an email from within the application, you can take a look at MFMailComposeViewController

You can simply instantiate this view controller, set the fields as subject, cc... and present it.

Taken from the documentation:

  1. Check that the service is available (it's not available in the simulator, for example)
if !MFMailComposeViewController.canSendMail() {
    print("Mail services are not available")
    return
}
  1. Instantiate the view controller, set the delegate and present it
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self

// Configure the fields of the interface.
composeVC.setToRecipients(["[email protected]"])
composeVC.setSubject("Hello!")
composeVC.setMessageBody("Hello from California!", isHTML: false)

// Present the view controller modally.
self.present(composeVC, animated: true, completion: nil)
  1. Dismiss when the mail is sent or the user cancelled
func mailComposeController(controller: MFMailComposeViewController,
                           didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    // Check the result or perform other tasks.

    // Dismiss the mail compose view controller.
    controller.dismiss(animated: true, completion: nil)
}

Upvotes: 2

Related Questions