其视图不在窗口层次结构中 – 电子邮件表单
我在appdelegate中从viewcontroller调用一个方法。 当我testingfunction时,我只是使用NSLog消息,它工作正常(所以viewcontroller和appdelegate之间的连接是好的)。 一旦我将电子邮件表单添加到此方法中,问题就出现了。 我收到的消息是:
Warning: Attempt to present <MFMailComposeViewController: 0x1fdc3990> on <ViewController: 0x1fd9e3b0> whose view is not in the window hierarchy!
任何人知道该怎么办? 我知道有很多话题是“谁的观点不在窗口层级”的问题,但他们都没有帮助我。
ViewController.m
... -(void)mail{ NSLog(@"blablabla"); if ([MFMailComposeViewController canSendMail]) { MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init]; mail.mailComposeDelegate = self; [mail setSubject:@"Hello and welcome!"]; NSArray *toRecipients = [NSArray arrayWithObject:@"tomas.javnicky@gmail.com"]; [mail setToRecipients:toRecipients]; [mail setCcRecipients:toRecipients]; NSString *emailBody = @"Hey all!"; [mail setMessageBody:emailBody isHTML:NO]; mail.modalPresentationStyle = UIModalPresentationPageSheet; [self presentViewController:mail animated:YES completion:nil]; } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"E-mail is not supported on your device" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } } -(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{ switch (result) { case MFMailComposeResultCancelled: break; case MFMailComposeResultSaved: NSLog(@"mail saved"); break; case MFMailComposeResultSent: NSLog(@"mail sent"); break; case MFMailComposeResultFailed: NSLog(@"mail failed"); break; } [self dismissViewControllerAnimated:YES completion:nil]; } ...
Appdelegate.m
... -(void)something { ViewController * vc = [[ViewController alloc] init]; [vc mail]; } ...
这是什么解决了我的问题:
- (void)something { ViewController *rootViewController = (ViewController*)self.window.rootViewController; [rootViewController mail]; }
另请查看rmaddy的答案以获取更多信息。
现在你已经发布了代码,问题是显而易见的。 你创build一个视图控制器,但你永远不会显示它(在something
方法)。 然后你在这个未显示的视图控制器( mail
)上调用一个方法,试图从未显示的视图控制器显示邮件视图控制器。 这是导致错误的原因。
您需要显示已经显示的视图控制器的邮件控制器(例如可能是rootViewController
)。
什么是你的ViewController
类的重点?