I am trying to present a MFMailComposeViewController
in my SwiftUI app an I get the error.
Found unexpected null pointer value while trying to cast value of type 'MFMailComposeViewController' (0x1272f5248) to 'UIViewController' (0x11fdb4418)
SwiftUI
struct ListView: View {
@State var isShowingMailView = false
@State var email = "[email protected]"
var body: some View {
ScrollView(showsIndicators: isMac ? true : false) {
HStack(spacing: 16) {
Text("Support")
Spacer()
}
.onTapGesture {
self.isShowingMailView.toggle()
}
.disabled(!MFMailComposeViewController.canSendMail())
.sheet(isPresented: $isShowingMailView) {
MailView(email: email)
}
Spacer()
} // SCROLLVIEW
}
}
MailView
struct MailView : UIViewControllerRepresentable{
var email: String
typealias UIViewControllerType = MFMailComposeViewController
func updateUIViewController(_ uiViewController: MFMailComposeViewController, context: Context) {
}
func makeUIViewController(context: Context) -> MFMailComposeViewController {
if MFMailComposeViewController.canSendMail(){
let view = MFMailComposeViewController()
view.mailComposeDelegate = context.coordinator
view.setToRecipients([email])
return view
} else {
return MFMailComposeViewController()
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator : NSObject, MFMailComposeViewControllerDelegate{
var parent : MailView
init(_ parent: MailView){
self.parent = parent
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}
}
If your device is not able to send mail the MFMailComposeViewController can't be init.
You will see this in the log [MFMailComposeViewController] Unable to initialize due to + [MFMailComposeViewController canSendMail] returns NO.
You need to check the canSendMail
before call your MailView instead to check inside the makeUIViewController
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With