如何在移动到下一个视图控制器后显示警报?

问题描述 投票:0回答:1

我正在使用此代码从另一个类调用

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
,并且我看不到警报。如何解决这个问题?

ios swift uikit uialertcontroller
1个回答
0
投票

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.