2016-12-21 97 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

的问题是你写的mailOpen函数内didFinishWithResult:委托方法,因此它永远不会被调用,而解聘代码不会被永远执行。

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庆安)。 –

+2

@PEEJWEEJ没有理由编辑某人的答案只是为了改变花括号的位置。不同的人喜欢不同的风格。 – rmaddy

+0

@deville:没有官方文件说明应该遵循哪种风格。我更喜欢这种风格,因为对于我来说,匹配打开和关闭大括号非常容易。 –

-2

这里:

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

你解雇自己的视图控制器,而不是MFMailComposeViewController

它应该是:

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