有什么方法可以创建常见的电子邮件发送方法(例如:-在应用中与我们联系)

时间:2018-08-25 12:11:31

标签: ios swift swift4

我遇到错误:-//无法将'UIViewController'类型的值分配为'MFMailComposeViewControllerDelegate吗?' //

如果我没有分配代表,则在单击消息VC中的“取消”后,我将无法回来。

请参阅以下代码:- 现在我正在做这样的事情:-

extension UIViewController { 

func contactUs() {

    if MFMailComposeViewController.canSendMail() {

        mc.mailComposeDelegate = self

                    if let name = CurrentUser.name, let phoneNo = CurrentUser.phone {
                        mc.setMessageBody("\n\n\nThanks & Regards\n\(name)\n\(phoneNo)", isHTML: false)
                    }
                 mc.setSubject(emailTitle)
                 mc.setToRecipients(toRecipents)
                 self.present(mc, animated: true, completion: nil)      
       }
    }
}


extension ViewController:  MFMailComposeViewControllerDelegate {

func mailComposeController(_ controller:MFMailComposeViewController, didFinishWith result:MFMailComposeResult, error:Error?) {
    switch result {
    case .cancelled:
        print_debug("Mail cancelled")
    case .saved:
        print_debug("Mail saved")
    case .sent:
        print_debug("Mail sent")
    case .failed:
        print_debug("Mail sent failure: \(error?.localizedDescription ?? "Mail not sent")")
    default:
        break
    }
    self.dismiss(animated: true, completion: nil)
  }
}

1 个答案:

答案 0 :(得分:0)

嗨,Vipul,您遇到了错误,因为在代码中您将viewcontroller分配给self,所以您需要做的是对该控制器进行类型转换

mc.mailComposeDelegate = self as? MFMailComposeViewControllerDelegate

这将解决您的问题,我也建议您像这样为MFMailComposeViewControllerDelegate提供默认实现

import MessageUI

extension MFMailComposeViewControllerDelegate {

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

        switch result {
        case .cancelled:
            print_debug("Mail cancelled")
        case .saved:
            print_debug("Mail saved")
        case .sent:
            print_debug("Mail sent")
        case .failed:
            print_debug("Mail sent failure: \(error?.localizedDescription ?? "Mail not sent")")
        default:
            break
        }
        controller.dismiss(animated: true, completion: nil)

    }

}

,您无需设置mc.mailComposeDelegate