簡體   English   中英

帶委托的Swift擴展(UIViewController)

[英]Swift Extension with delegation (UIViewController)

我需要能夠在我的應用程序中的多個視圖控制器中發送電子郵件。 代碼相同,采用三個參數-收件人地址,正文和主題。 如果在設備上配置了Mail,請使用視圖控制器作為委托初始化MFMailComposeViewController。 如果未配置郵件,則引發錯誤。 還將當前視圖控制器設置為mailComposeDelegate以偵聽回調。 如何使用Swift擴展來實現它(將擴展中的委托設置為主要問題)?

我認為您應該為此類問題創建服務類,以便可以在其他應用程序中重用。

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

現在,您可以使用以下代碼從所有三個Controller發送郵件。

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

        }

記得我曾經用過簡單的Clouser(completion),它以String作為參數來告知它是成功還是失敗,但是您可以根據您的要求進行編寫。此外,您還可以使用委托模式代替clouser或callback。

此類服務類的主要優勢是依賴注入。有關更多詳細信息: https : //medium.com/@JoyceMatos/dependency-injection-in-swift-87c748a167be

創建一個全局函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM