MFMailComposeViewController отказывается отклонять

Это сводит меня с ума. Этот фрагмент кода позволяет пользователю отправить электронное письмо с изображением, созданным в приложении. Все работает отлично, кроме self.dismiss(animated: true, completion: nil) - MFMailComposeViewController не сбрасывается.

Я использовал эти три возможные проблемы https://stackoverflow.com/a/13217443/5274566 в качестве начала решения проблемы. , но все равно не получится. Контроллер остается, несмотря на то, что письмо было отправлено или cancel было нажато.

Добавлена ​​реализация протокола MFMailComposeViewControllerDelegate.

func mailOpen(alertAction: UIAlertAction) {
    if MFMailComposeViewController.canSendMail() {
        let mailcontroller = MFMailComposeViewController()
        mailcontroller.mailComposeDelegate = self;
        mailcontroller.setSubject("Subject")
        let completeImage = newImage! as UIImage
        mailcontroller.addAttachmentData(UIImageJPEGRepresentation(completeImage, CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "Image")
        mailcontroller.setMessageBody("<html><body><p>Message</p></body></html>", isHTML: true)

        self.present(mailcontroller, animated: true, completion: nil)
    } else {
        let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send the e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "Got it!")
        sendMailErrorAlert.show()
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        self.dismiss(animated: true, completion: nil)
    }
}//end of mail

person Mate    schedule 21.12.2016    source источник


Ответы (2)


Проблема в том, что вы написали метод делегата didFinishWithResult: внутри функции mailOpen, поэтому он никогда не будет вызываться, и код отклонения никогда не будет выполняться.

func mailOpen(alertAction: UIAlertAction)
{
    if MFMailComposeViewController.canSendMail()
    {
        let mailcontroller = MFMailComposeViewController()
        mailcontroller.mailComposeDelegate = self;
        mailcontroller.setSubject("Subject")
        let completeImage = newImage! as UIImage
        mailcontroller.addAttachmentData(UIImageJPEGRepresentation(completeImage, CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "Image")
        mailcontroller.setMessageBody("<html><body><p>Message</p></body></html>", isHTML: true)

        self.present(mailcontroller, animated: true, completion: nil)

    }
    else
    {

        let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send the e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "Got it!")
        sendMailErrorAlert.show()
    }
}//end of mail

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?)
{
    self.dismiss(animated: true, completion: nil)
}
person Midhun MP    schedule 21.12.2016
comment
Открывающую фигурную скобку не следует оборачивать (см. github.com/raywenderlich/swift-style-guide# интервал). - person Andrii Chernenko; 21.12.2016
comment
@PEEJWEEJ Нет причин редактировать чей-то ответ только для того, чтобы изменить расположение фигурных скобок. Разные люди предпочитают разные стили. - person rmaddy; 22.12.2016
comment
@deville: Нет официального документа, в котором говорится, какому стилю следует следовать. Я предпочитаю этот стиль, так как мне проще сопоставить открывающую и закрывающую фигурную скобку. - person Midhun MP; 24.12.2016
comment
Спасибо! Глупая ошибка - person Mate; 31.12.2016

здесь:

self.dismiss(animated: true, completion: nil)

вы отклоняете свой собственный ViewController, а не MFMailComposeViewController

Должен быть:

controller.dismiss(animated: true, completion: nil)
person GetSwifty    schedule 21.12.2016