Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application is crashing on MFMailComposeViewController object in IOS7

I am creating

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

but picker is nil yet and application is crashing with error Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target. It is working fine in simulator but crashing in Device . How can is use MFMailComposerViewController with IOS 7.

like image 543
Sachin Vani Avatar asked Sep 27 '13 13:09

Sachin Vani


2 Answers

You should check if MFMailComposeViewController is able to send your mail just before trying to send it (for example user could not have any mail account on the iOS device).

So in your case for Objective-C:

MFMailComposeViewController *myMailCompose = [[MFMailComposeViewController alloc] init];

if ([MFMailComposeViewController canSendMail]) {
    myMailCompose.mailComposeDelegate = self;
    [myMailCompose setSubject:@"Subject"];
    [myMailCompose setMessageBody:@"message" isHTML:NO];
    [self presentViewController:myMailCompose animated:YES completion:nil];
} else {
    // unable to send mail, notify your users somehow
}

Swift 3:

let myMailCompose = MFMailComposeViewController()

if MFMailComposeViewController.canSendMail() {
    myMailCompose.mailComposeDelegate = self
    myMailCompose.setSubject("Subject")
    myMailCompose.setMessageBody("message", isHTML: false)
    self.present(myMailCompose, animated: true, completion: nil)
} else {
    // unable to send mail, notify your users somehow
}
like image 82
Yauheni Shauchenka Avatar answered Sep 22 '22 17:09

Yauheni Shauchenka


Though checking if one can send mail helps avoiding the application crashing, it would be nice to find out, why it's actually happening. (in my case, the same app crashes on iPhone 4s but not in iPhone 5)

UPDATE: I've found following (if the reason of crashing is interesting for You!): MFMailComposeViewController produces a nil object As I used the gmail app, I didn't activated the mail support by apple. After reading this I've activated it and ... ta-da ... everything works fine!

like image 27
chAlexey Avatar answered Sep 26 '22 17:09

chAlexey