Sameeha Sameeha - 4 months ago 25
iOS Question

NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target

I created an email using Xcode 7.3 beta 3 .. I go the code from appcoda

- (IBAction)showEmail:(id)sender {
// Email Subject
NSString *emailTitle = @"Test Email";
// Email Content
NSString *messageBody = @"iOS programming is so fun!";
// To address
NSArray *toRecipents = [NSArray arrayWithObject:@"support@appcoda.com"];

MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];

// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];

}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(@"Mail cancelled");
break;
case MFMailComposeResultSaved:
NSLog(@"Mail saved");
break;
case MFMailComposeResultSent:
NSLog(@"Mail sent");
break;
case MFMailComposeResultFailed:
NSLog(@"Mail sent failure: %@", [error localizedDescription]);
break;
default:
break;
}

// Close the Mail Interface
[self dismissViewControllerAnimated:YES completion:NULL];
}


But it gave me an error (as you can see below) after running the application on iPhone


* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target .'* First throw call stack:()libc++abi.dylib: terminating with uncaught exception of type NSException

Answer

NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target -- It means you try to implement the nil objcet on target check once if it is nil or not

MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
if (!mc) {  
  //When the device has not added mailViewController mail account is empty , the following present view controller causes the program to crash here
NSLog(@"no email accounts are set up in your device");  
return;  
} 

sample tutorial

Comments