2016-12-21 16 views
0

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

ответ

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

скобка Открытие не должны быть обернуты (см. https://github.com/raywenderlich/swift-style-guide#spa Cing). –

+2

@PEEJWEEJ Нет причин редактировать чей-то ответ, чтобы изменить расположение фигурных скобок. Различные люди предпочитают разные стили. – rmaddy

+0

@deville: Нет официального документа, в котором говорится, какой стиль следует соблюдать. Я предпочитаю этот стиль, так как мне очень легко подобрать подходящую открывающую и закрывающую скобу. –

-2

здесь:

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

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

Оно должно быть:

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