MFMailComposeViewController, Swift 4, Xcode 9

Đorđe Nilović picture Đorđe Nilović · Feb 9, 2018 · Viewed 7.6k times · Source

I have a problem with MFMailComposeViewControllerDelegate function.

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

The warning says

Instance method 'mailComposeController(:didFinishWith:error:)' nearly matches optional requirement 'mailComposeController(:didFinishWith:error:)' of protocol 'MFMailComposeViewControllerDelegate'

Make 'mailComposeController(_:didFinishWith:error:)' private to silence this warning

I need to return the user to the App and dismiss MFMailComposeViewController after clicking cancel and this function is not triggered.

Yes, I added the delegate composeVC.mailComposeDelegate = self

If someone had a similar problem, I would appreciate the help. Thanks

EDIT

This behavior is happening only when I set the language to Swift 4. I just went back few commits and it's working perfectly fine with Swift 3.2

Basically, this is the code:

class TechSupportVC: UIViewController, MFMailComposeViewControllerDelegate {
    let composeVC = MFMailComposeViewController()

override func viewDidLoad() {
    super.viewDidLoad()

    composeVC.mailComposeDelegate = self
    composeVC.setToRecipients(["[email protected]"])
    composeVC.setSubject("My message")
}

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

@IBAction func sendPressed(_ sender: Any) {
    guard MFMailComposeViewController.canSendMail() else {
        showMailServiceErrorAlert()
        return
    }

    composeVC.setMessageBody("Test credentials: \(firstAndLastNameTextField.text!)\nPhone: \(numberTextField.text!)\n\n\(messageTextView.text!)", isHTML: false)

    self.present(composeVC, animated: true, completion: nil)
}

}

Answer

Boris Y. picture Boris Y. · Feb 13, 2018

It wasn't possible for me to apply Đorđe's solution, this other answer helped me.

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

Adding Swift. prefix to Error? solves the problem.