Deepak Sharma
Deepak Sharma

Reputation: 6477

Swift Extension with delegation (UIViewController)

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)?

Upvotes: 0

Views: 1122

Answers (2)

Bhavesh.iosDev
Bhavesh.iosDev

Reputation: 942

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:["[email protected]"],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

Upvotes: 4

Alex Bailey
Alex Bailey

Reputation: 793

Create a global function:

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

Upvotes: 0

Related Questions