Search code examples
iosswiftmfmailcomposeviewcontroller

how to dismiss mail view controller after tapping send or cancel button


while sending mail, after tapping send or cancel button view controller stays there and app stalls.

//swift 2.2 ; xcode 7.3.1 ;

  if( MFMailComposeViewController.canSendMail() ) {
            print("Can send email.")
        }

        var subjectText = "Verification"
        var toReceipients = ["[email protected]"]


        // var msgBody = "Verified"


        var mc:MFMailComposeViewController = MFMailComposeViewController()
        mc.mailComposeDelegate = self

        mc.setSubject(subjectText)
        mc.setMessageBody("Verified", isHTML: false)

        mc.setToRecipients(toReceipients)
        self.presentViewController(mc, animated: true, completion: nil)



    }

    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {



        self.dismissViewControllerAnimated(true, completion: nil)

    }

Solution

  • I think @rmaddy answer your question in his comment, nevertheless I going to explain you what's happening. You're trying to dismiss the UIViewController that presents the MFMailComposeViewController not the MFMailComposeViewController.

    As Apple specify in his documentation:

    The mail compose view controller is not dismissed automatically. When the user taps the buttons to send the email or cancel the interface, the mail compose view controller calls the mailComposeController:didFinishWithResult:error: method of its delegate. Your implementation of that method must dismiss the view controller explicitly.

    So you need to set the method in this way:

     func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    
        // Dismiss the mail compose view controller.
        controller.dismissViewControllerAnimated(true, completion: nil)
    }
    

    I hope this help you.