单击警报按钮以显示 MFMailComposeViewController

Click alert button to show MFMailComposeViewController

单击警报按钮时尝试使用 MFMailComposeViewController。但是当我单击警报按钮时,控制器不会弹出。代码如下。我使用了扩展程序,并且在单击警报按钮时尝试调用 sendmail 函数。

extension Alert:MFMailComposeViewControllerDelegate {
    func sendmail(){
        let mailComposeViewController = configureMailController()
        if MFMailComposeViewController.canSendMail() {
            let VC = storyboard?.instantiateViewController(withIdentifier: "MainVC")
            VC?.present(mailComposeViewController, animated: true, completion: nil)
        } else {
            showMailError()
        }
    }

    func configureMailController() -> MFMailComposeViewController {
        let mailComposerVC = MFMailComposeViewController()
        let VC = storyboard?.instantiateViewController(withIdentifier: "MainVC")
        mailComposerVC.mailComposeDelegate = VC as? MFMailComposeViewControllerDelegate

        mailComposerVC.setToRecipients(["**"])
        mailComposerVC.setSubject("**")
        mailComposerVC.setMessageBody("\n\n\n\nModel: \nSistem versiyon: )\nuygulamaversiyon:", isHTML: false)

        return mailComposerVC
    }

    func showMailError() {
        let sendMailErrorAlert = UIAlertController(title: "Could not send email", message: "Your device could not send email", preferredStyle: .alert)
        let dismiss = UIAlertAction(title: "Ok", style: .default, handler: nil)
        sendMailErrorAlert.addAction(dismiss)
        let VC = storyboard?.instantiateViewController(withIdentifier: "MainVC")
        VC?.present(sendMailErrorAlert, animated: true, completion: nil)
    }

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

您的代码尝试在您使用 instantiateViewController 创建的新视图控制器上显示邮件视图控制器(以及错误警报)。由于这个新 VC 本身不是您应用 VC 层次结构的一部分,因此它和邮件 VC 都不会出现在屏幕上。

要完成此工作,您可以将 应用程序一部分的视图控制器传递到 sendmail 方法中:

func sendmail(_ root: UIViewController) {
  ...
  root.present(mailComposeViewController, animated: true, completion: nil)
  ...

或者您可以使用全球可访问的 VC 您的应用程序;在使用根 VC 的简单应用程序中应该可以工作:

func sendmail() {
  ...
  let root = UIApplication.shared.keyWindow?.rootViewController
  root?.present(mailComposeViewController, animated: true, completion: nil)
  ...

我建议第一种方法,因为它更灵活(例如,它允许您在任何地方打开邮件屏幕,即使您的 VC 层次结构变得更加复杂)。