单击警报按钮时尝试使用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)
}
}
答案 0 :(得分:0)
您的代码尝试在使用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层次结构变得更复杂)。