How to open mail app from Swift

前端 未结 15 1342
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 20:18

Im working on a simple swift app where the user inputs an email address and presses a button which opens the mail app, with the entered address in the address bar. I know ho

15条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 20:40

    In the view controller from where you want your mail-app to open on the tap.

    • At the top of the file do, import MessageUI.
    • Put this function inside your Controller.

      func showMailComposer(){
      
        guard MFMailComposeViewController.canSendMail() else {
             return
        }
        let composer = MFMailComposeViewController()
        composer.mailComposeDelegate = self
        composer.setToRecipients(["abc@gmail.com"]) // email id of the recipient
        composer.setSubject("testing!!!")
        composer.setMessageBody("this is a test mail.", isHTML: false)
        present(composer, animated: true, completion: nil)
       }
      
    • Extend your View Controller and conform to the MFMailComposeViewControllerDelegate.

    • Put this method and handle the failure, sending of your mails.

      func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        if let _ = error {
            controller.dismiss(animated: true, completion: nil)
            return
        }
        controller.dismiss(animated: true, completion: nil)
      }
      

提交回复
热议问题