MFMailComposeViewController init no arguments

219 views Asked by At

i'm trying to create the following extension in Swift:

    extension MFMailComposeViewController {

      convenience init(document: Document) {
        self.init()

        // do some configuration...
        setMessageBody("BlaBlaBla", isHTML: false)
      }

    }

However I am not able to get this to compile:

Cannot invoke 'MFMailComposeViewController.init' with no arguments

Which seems strange to me because MFMailComposeViewController definitely has an initialiser with no arguments.

Any help on how to fix this issue would be greatly appreciated.

2

There are 2 answers

2
Saad On

For sublcassing use super.init() instead of self.init() and for extensions self

0
bubuxu On

The reason you got the error is if you run the app on the device or simulator without checking canSendMail method, you will get a nil object by initiating it with empty parameter (the default init method).

extension MFMailComposeViewController {

    convenience init?(document: UIImage) {

        guard MFMailComposeViewController.canSendMail() else { return nil }

        self.init()
        // continue setup the controller


    }

}

You can test this on a simulator without setting up any email accounts by the following code:

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let controller: MFMailComposeViewController? = MFMailComposeViewController()
        guard let mail = controller else { return }
        present(mail, animated: true, completion: nil)
    }

}