我正在使用此代码从另一个类调用
MFMailComposeViewController
:
一些ViewController:
class SomeController: UIViewController {
func contactWithDeveloper() {
let detailController = Mail()
detailController.messageTitle = "1"
detailController.messageAddress = "1"
detailController.messageText = "1"
detailController.errorTitle = "1"
detailController.errorMessage = "1"
detailController.modalPresentationStyle = .overFullScreen
self.present(detailController, animated: false, completion: nil)
}
}
邮件视图控制器:
class Mail: UIViewController, MFMailComposeViewControllerDelegate {
var messageTitle = ""
var messageAddress = ""
var messageText = ""
var errorTitle = ""
var errorMessage = ""
override func viewDidLoad() {
super.viewDidLoad()
send(title: messageTitle, address: [messageAddress], message: messageText, errorTitle: errorTitle, errorMessage: errorMessage)
}
func send(title: String, address: [String], message: String, errorTitle: String, errorMessage: String) {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setSubject(title)
mail.setToRecipients(address)
mail.setMessageBody(message, isHTML: false)
present(mail, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: dismissHandler))
self.present(alert, animated: true, completion: nil)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
dismiss(animated: false, completion: nil)
}
func dismissHandler(aler: UIAlertAction) {
dismiss(animated: false, completion: nil)
}
}
此代码片段
if MFMailComposeViewController.canSendMail()
工作正常,我可以看到MFMailComposeViewController
。但如果我无法发送消息,则不会调用 UIAlertController
,并且我看不到警报。如何解决这个问题?
在
viewDidLoad
中提出警报还为时过早。您可以用 viewWillAppear
或 viewDidAppear
来完成。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if MFMailComposeViewController.canSendMail() {
// ...
} else {
let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: dismissHandler))
self.present(alert, animated: true, completion: nil)
}
}