MailComposer не закрыт

Я пытался использовать MailComposer. Вот код, который я использовал:

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

И затем, когда пользователь нажимает кнопку:

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)
}

И при увольнении:

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

Обнаружено, что если кнопка нажата в первый раз, компоновщик почты работает нормально, независимо от того, выбираю ли я отправить или отменить.

Однако после того, как я отправлю/отменю во второй раз, составитель почты не может быть закрыт. У отправки есть ответ, который может отправить электронное письмо, но интерфейс компоновщика почты никогда не закрывается.

Я обнаружил, что функция func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) больше не срабатывает после первого раза.

Любые подсказки?


person user6539552    schedule 20.05.2017    source источник


Ответы (3)


Вы не должны использовать один и тот же экземпляр MFMailComposeViewController снова..

Попробуй это

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)
    }
}
person Bilal    schedule 20.05.2017
comment
Отлично, я не знал, что я не могу повторно использовать один и тот же экземпляр MFMailComposeViewController - каждый раз, если вам нужен компоновщик почты, вы должны создавать НОВЫЙ экземпляр. - person DennyDog; 01.12.2019

Ну не знаю, что ты делаешь не так. Я думаю, вы используете Swift. Итак, я объясню вам, как вы можете реализовать это. Шаги:

1) import MessagesUI и добавить делегата MFMailComposeViewControllerDelegate

2) Добавьте эту функцию:

func configuredMailComposeViewController() -> MFMailComposeViewController {
    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self
    mailComposerVC.setToRecipients(["[email protected]"])
    mailComposerVC.setSubject("Sending you an in-app e-mail...")
    mailComposerVC.setMessageBody("Sending e-mail in-app is not so bad!", isHTML: false)

    return mailComposerVC
}

3) Вызовите вышеуказанную функцию в IBAction кнопки как:

let mailComposeViewController = configuredMailComposeViewController()
    if MFMailComposeViewController.canSendMail() {
        self.present(mailComposeViewController, animated: true, completion: nil)
    } else {
        // Show alert if user can't send mail
    }

4) Наконец, реализуйте метод делегата:

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

Правильно, дело в том, что я повторно использую экземпляр emailController.

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

}

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

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

Это работает сейчас.

person user6539552    schedule 20.05.2017