0

I need ability to send email in a number of view controllers in my app. The code is same, take three params -- recipient address, body, and subject. If Mail is configured on device, initialize MFMailComposeViewController with the view controller as delegate. If Mail is not configured, throw an error. Also set current view controller as mailComposeDelegate to listen to callbacks. How does one use Swift extension to achieve it (setting delegate in extension being the main issue)?

Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131

2 Answers2

4

I think you should create service Class for this type of Problem so it can be reused in other Application.

class MailSender : NSObject , MFMailComposeViewControllerDelegate {
    var currentController : UIViewController!
    var recipient : [String]!
    var message : String!
    var compltion : ((String)->())?
    init(from Controller:UIViewController,recipint:[String],message:String) {
        currentController = Controller
        self.recipient = recipint
        self.message  = message
    }

    func sendMail() {
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients(recipient)
            mail.setMessageBody(message, isHTML: true)
            currentController.present(mail, animated: true)
        } else {
            if compltion != nil {
                compltion!("error")
            }
        }
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        if compltion != nil {
            compltion!("error")
        }
        controller.dismiss(animated: true)
    }
}

now you can send mail From All three Controller using Following Code.

let mailsender = MailSender(from: self,recipint:["example@via.com"],message:"your message")
        mailsender.sendMail()
        mailsender.compltion = { [weak self] result in
            print(result)
            //other stuff

        }

remember I have used simple Clouser(completion) that take String as Argument to inform whether it is success or fails but you can write as per your requirment.in addition you can also use delegate pattern instead of clouser or callback.

main advantage of this type of service Class is dependancy injection.for more details : https://medium.com/@JoyceMatos/dependency-injection-in-swift-87c748a167be

Bhavesh.iosDev
  • 924
  • 9
  • 27
0

Create a global function:

func sendEmail(address: String, body: String, subject: String, viewController: UIViewController) {
    //check if email is configured or throw error...
}
Alex Bailey
  • 793
  • 9
  • 20