johnCole
johnCole

Reputation: 103

Implementing MailComposeController in tableView

I have created the setting page in TableView. When I tap row 0 UIActivityViewController is called. When I tap row2 MailComposeController is called.

MailComposeController is called, but when I tap cancel or send button on mail screen it does not work.

Here is the code。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if indexPath.row == 0 {

            let message = "Hey download my app [LINK]"
            let shareView = UIActivityViewController(activityItems: [message], applicationActivities: nil)
            self.present(shareView, animated: true, completion: nil)

        } else if indexPath.row == 1 {
            let mailCompose = MFMailComposeViewController()

            mailCompose.mailComposeDelegate = self

            mailCompose.setToRecipients(["[email protected]"])

            mailCompose.setSubject("feedback")

            mailCompose.setMessageBody("text", isHTML: false)

            if MFMailComposeViewController.canSendMail()

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

            else{

                print("error...!")

            }
        }



        func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {

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

        }

Upvotes: 0

Views: 80

Answers (2)

Rahul Umap
Rahul Umap

Reputation: 2859

Implement the delegate methods of Mail composer on click of send and cancel button:

Here are the Delegates methods which you need to implement :

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: {
        switch (result)
        {
        case .cancelled:
            break
        case .saved:
            break;
        case .sent:
             AppUtility.showAlert(message: kEmailSentSuccessMessage, isSuccess: true)
            break;
        case .failed:
            AppUtility.showAlert(message: kEmailSentFailureMessage, isSuccess: true)
            break;
        }
    })
}

Use breakpoint to see what exactly going on the click of send or cancel. and make sure that you have created the MailComposer object locally . since this object is going to send and cancel the mail each time .

Upvotes: 1

chengsam
chengsam

Reputation: 7405

You have to put the delegate method in the ViewController but not in the tableView:didSelectRowAt method:

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

Upvotes: 2

Related Questions