2

I'm trying to do what the title says but when i tap the button to open mail my app crashes when i don't have mail app installed. can you help me sort this out?

Code:

if UIApplication.shared.canOpenURL(URL(string: "mailto://")!) {
            // Mail is installed. Launch Mail and start function:
            let toRecipients = ["oExample@gmail.com"]

        let mc: MFMailComposeViewController = MFMailComposeViewController()

        mc.mailComposeDelegate = self

        mc.setToRecipients(toRecipients)
        mc.setSubject("Why does it crash?")

        mc.setMessageBody("שם הבר: \(CrashNameField.text!) \n\nעיר: \(CrashReasonNameField.text!)", isHTML: false)

        self.present(mc, animated: true, completion: nil)

    }else {
            // Mail is not installed. Launch AppStore to install Mail app
            UIApplication.shared.openURL(URL(string: "https://itunes.apple.com/gb/app/mail/id1108187098?mt=8")!)
        }
    }

Crash gathered logs :

libc++abi.dylib: terminating with uncaught exception of type NSException crashes on line : class AppDelegate: UIResponder, UIApplicationDelegate{ . Extra info : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target

Óscar López
  • 232,561
  • 37
  • 312
  • 386
RandomGeek
  • 303
  • 5
  • 20
  • What is the crash? Which line does it crash on? – Paulw11 Jul 19 '17 at 10:37
  • sorry , should have included that in. Its saying : `libc++abi.dylib: terminating with uncaught exception of type NSException` crashes on line : `class AppDelegate: UIResponder, UIApplicationDelegate{` . Extra info : `Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target` – RandomGeek Jul 19 '17 at 10:41
  • It looks like all you need to do is check to see if `mc == nil` – Paulw11 Jul 19 '17 at 10:48
  • can you show me how can it be done... sorry, I'm still a newbie... – RandomGeek Jul 19 '17 at 10:50
  • `if mc != nil { // your existing code } else { // prompt to install mail client }` – Paulw11 Jul 19 '17 at 11:40

1 Answers1

3

try this way

 var picker = MFMailComposeViewController()
    if MFMailComposeViewController.canSendMail() {
        picker.mailComposeDelegate = self
        picker.setSubject("Test mail")
        picker.setMessageBody(messageBody.text, isHTML: true)
        present(picker as? UIViewController ?? UIViewController(), animated: true) { _ in }
    }

original post here

Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73