iOS:应用程序试图在目标上呈现空模态视图控制器

39

我正在开发一个应用程序,要求在UIAlertView的按钮点击时打开电子邮件撰写器。

邮件消息体中的消息是从UITextView复制的。我正在使用以下代码片段:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0)
  {
      // opening message composer
  }
else
  {
   MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"Test mail"];
    [picker setMessageBody:messageBody.text isHTML:YES];
    [self presentViewController:picker animated:YES completion:NULL];
  }
}
 // mail compose delegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
      [self dismissViewControllerAnimated:YES completion:NULL];
}

但问题在于我收到了一个错误,说应用尝试在目标上呈现一个无效的模态视图控制器。我们该如何在iOS 7中打开默认的邮件撰写器?

3个回答

83

据苹果公司表示,您应该在发送邮件之前检查MFMailComposeViewController是否能够发送您的邮件。

if ([MFMailComposeViewController canSendMail]) {
     MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"Test mail"];
    [picker setMessageBody:messageBody.text isHTML:YES];
    [self presentViewController:picker animated:YES completion:NULL];
}

Swift:

if MFMailComposeViewController.canSendMail() else {
// Send mail code
}

参考:Apple Dev url



1
守卫机制非常棒! - Naeem
但是为什么文本消息(MFMessageComposeViewController)不需要这个检查呢?我有一个没有SIM卡的测试设备,从技术上讲,它不应该能够发送短信,但是在没有进行检查的情况下它可以正常工作(没有抛出异常)...为什么?谢谢。 - RainCast
那么,不再在模拟器上测试发送邮件的用户界面了吗? - Nicolas Miari
用户的设备可能没有配置电子邮件帐户。因此,在模拟器上进行测试可以捕获缺失的保护。添加canSendMail后,我们将不得不依赖于设备测试。 - John Pang

17

Swift 4 版本

guard MFMailComposeViewController.canSendMail() else {
    print("Mail services are not available")
    return
}
sendEmail()

11

忘记在设备设置中配置邮件帐户也可能导致此错误。请检查您的设备是否配置了邮件帐户。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接