ios - 带委托(delegate)的 Swift 扩展 (UIViewController)

标签 ios swift uiviewcontroller swift4 swift-extensions

我需要能够在我的应用程序中的多个 View Controller 中发送电子邮件。代码相同,采用三个参数——收件人地址、正文和主题。如果在设备上配置了邮件,则使用 View Controller 作为委托(delegate)初始化 MFMailComposeViewController。如果未配置 Mail,则抛出错误。还将当前 View Controller 设置为 mailComposeDelegate 以监听回调。如何使用 Swift 扩展来实现它(在扩展中设置委托(delegate)是主要问题)?

最佳答案

我认为您应该为此类问题创建服务类,以便它可以在其他应用程序中重用。

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 作为参数来通知它是成功还是失败,但您可以根据您的要求编写。此外,您还可以使用委托(delegate)模式而不是 clouser 或回调。

这种类型的服务类的主要优点是依赖注入(inject)。有关更多详细信息:https://medium.com/@JoyceMatos/dependency-injection-in-swift-87c748a167be

关于ios - 带委托(delegate)的 Swift 扩展 (UIViewController),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53268831/

相关文章:

ios - 无法执行委托(delegate)

ios - 在 iOS 中停止 View 旋转

swift - 根据具有最小和最大偏移量的中心点计算随机 X 和 Y

ios - 在所有 View Controller 中创建警报功能 - swift

ios - Swift 2 - 带有自定义 UITableView 单元格的 UIViewController

ios - 为 iOS 或 OSX 开发蓝牙 4.0 BLE 应用程序的成本?

javascript - Phonegap 设备准备好在 iOS 中使用 Cordova 2.2.0 不触发

ios - 在 Webview 中打开按钮链接

ios - Int 数组到 Int 标准方法

objective-c - 卡住试图从一个 Viewcontroller 中的 UILabel 获取 NSString 以放置在另一个 Viewcontroller 的 UITextView 中