我使用Xcode 7.3 beta 3创建了一封电子邮件。我从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];
}
但是在iPhone上运行应用程序后,它给了我一个错误(如下所示)
*由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'应用程序试图在目标上显示一个nil模态视图控制器。'* 首先抛出调用堆栈:()libc ++ abi。 dylib:以NSException类型的未捕获异常终止
答案 0 :(得分:3)
NSInvalidArgumentException',原因:'应用程序尝试在目标上显示nil模态视图控制器 - 这意味着如果它是nil,则尝试在目标检查上实现nil objcet
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;
}
示例tutorial
答案 1 :(得分:1)
<强>夫特强>
使用if
if let mc: MFMailComposeViewController = MFMailComposeViewController() {
mc.mailComposeDelegate = self
mc.setSubject(emailTitle)
mc.setToRecipients(toRecipents)
self.presentViewController(mc, animated: true, completion: nil)
}