Reputation: 303
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.
Upvotes: 5
Views: 3618
Reputation: 753
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
}
Upvotes: 14
Reputation: 7212
Swift 3+
if !MFMailComposeViewController.canSendMail() {
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
composeVC.setToRecipients(["[email protected]"])
composeVC.setSubject("subject")
composeVC.setMessageBody("", isHTML: false)
self.present(composeVC, animated: true, completion: nil)
}
Upvotes: 0
Reputation: 845
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!
Upvotes: 3