2016-12-21 101 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)