iosswiftviewcontrollerdismissmfmailcomposer

MailComposer not dismissed


I tried to use MailComposer. Here is the code I used:

func setupMailer() {
    if MFMailComposeViewController.canSendMail() {
        emailController.mailComposeDelegate = self
        emailController.setToRecipients([]) // set the email address
        emailController.setSubject("BackgroundTask Test")
        emailController.setMessageBody("Message body", isHTML: false)
    }
}

And then when user presses a button:

func buttonPressed(button: UIButton) {
    debugPrint("buttonPressed", button)
    let path = dirpath.appendingPathComponent(filename)
    let data = NSData(contentsOfFile: path.path)
    emailController.mailComposeDelegate = self
    emailController.addAttachmentData(data! as Data, mimeType: "text/csv", fileName: filename)
    present(emailController, animated: true, completion: nil)
}

And when dismiss:

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

It is found that if the button is pressed for the first time, the mail composer works normally no matter I choose send or cancel.

However, after I send/cancel, for the 2nd time onwards, the mail composer cannot be dismissed. The send has response that can send the email, but the mail composer interface never dismiss.

I found that the function func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) is not triggered any more after the first time.

Any clues?


Solution

  • You are not supposed to use the same MFMailComposeViewController instance again..

    Try this

    func setupMailer() {
        if MFMailComposeViewController.canSendMail() {
            emailController = MFMailComposeViewController.init()
            emailController.mailComposeDelegate = self
            emailController.setToRecipients([]) // set the email address
            emailController.setSubject("BackgroundTask Test")
            emailController.setMessageBody("Message body", isHTML: false)
        }
    }