iosswiftstorekitmfmailcomposeviewcontrollermessageui

MFMailComposeViewController() not dismissed inside UIAlertAction


I have MFMailComposeViewController opening up inside UIAlertController and the code looks like this:

import StoreKit
import MessageUI

class SettingsListViewController: UIViewController, MFMailComposeViewControllerDelegate, UINavigationControllerDelegate {
// Some code adding the UITableView and etc
// ...
}

private extension SettingsListViewController {
    
    func didSelectShareCell(shareSectionCell: ShareSectionCell, _ tableView: UITableView, cellForRowAt indexPath: IndexPath) {
        switch shareSectionCell {
        // Some other cases...
        case .rate:
            let actionSheet = UIAlertController(title: "Feedback", message: "Are you enjoing the app?", preferredStyle: .alert)
            
            actionSheet.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
            
            actionSheet.addAction(UIAlertAction(title: "Yes, i love it", style: .default, handler: { action in
                SKStoreReviewController.requestReview()
            }))
            
            actionSheet.addAction(UIAlertAction(title: "No, this sucks", style: .default, handler: { action in
                guard MFMailComposeViewController.canSendMail() else {
                    // Alert info user
                    return
                }
                
                let composer = MFMailComposeViewController()
                composer.mailComposeDelegate = self
                composer.delegate = self
                composer.setToRecipients(["my mail"])
                composer.setSubject("i'm mad")
                composer.setMessageBody("Hey, i love your app but...", isHTML: false)
                
                self.present(composer, animated: true)
                
                func mailComposeController(_ controller: MFMailComposeViewController,
                                           didFinishWith result: MFMailComposeResult, error: Error?) {
                    self.dismiss(animated: true)
                }
                         
            }))
            
            present(actionSheet, animated: true)
            
        }
    }  
}


Everything works fine. Send mail window opens up, the mail being sent too and stuff but when it comes to pressing 'cancel' & 'send' buttons MFMailComposeViewController() isn't dismissed (have to swipe it down in order to dismiss it)

What can be wrong?


Solution

  • Put this delegate outside the function and inside the controller class. Also, dismiss like this controller.dismiss(animated: true)

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