我有一个简单的应用程序,它打开一个发送电子邮件的模态视图。我正在使用Xcode 4.2和iOS 5,并正在使用iOS模拟器进行测试。该应用程序崩溃了
由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:
'应用程序试图在目标上显示一个零模态视图控制器
。“
:
[self presentModalViewController:mailComposer animated:YES];
虽然我已经初始化了对象'mailComposer'。
类com_FirstViewController.m:
#import "com_FirstViewController.h"
...
@implementation com_FirstViewController
....
....
-(void)showEmailComposer {
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil)
{
if ([mailClass canSendMail]) {
NSLog(@"showEmailComposer: Calling displayComposerSheet");
[self displayComposerSheet];
} else {
NSLog(@"showEmailComposer: Calling launchMailAppOnDevice");
[self launchMailAppOnDevice];
}
}
else {
NSLog(@"showEmailComposer: Calling launchMailAppOnDevice");
[self launchMailAppOnDevice];
}
}
#pragma mark -
#pragma mark Compose Mail
-(void) displayComposerSheet {
mailComposer = [[MFMessageComposeViewController alloc] init];
mailComposer.messageComposeDelegate = self;
// Set the mail title
[mailComposer setTitle:@"Mail Title"];
// Set the recipients
NSArray *toRecipients = [NSArray arrayWithObject:@"user@company.com"];
[mailComposer setRecipients:toRecipients];
// EMail Body
NSString *mailBody = @"This is the mail body";
[mailComposer setBody:mailBody];
NSLog(@"present the modal view ctlr");
[self presentModalViewController:mailComposer animated:YES];
}
...
...
请指点什么?
答案 0 :(得分:55)
我也遇到过类似的问题。我分配了一个MFMailComposeViewController
的实例并尝试以模态方式呈现它。我也有例外:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target
这是因为在iPhone的设置中禁用了Mail选项。当设备中没有设置邮件帐户时也可能是这种情况。因此MFMailCompseViewController
实例将为nil
并以模态方式呈现它将导致崩溃。
我使用了canSendMail
的{{1}}方法解决了这个问题。
MFMailComposeViewController
答案 1 :(得分:16)
mailComposer = [[MFMessageComposeViewController alloc] init];
在我看来,是问题的根源。模拟器无法发送SMS消息,因此初始化方法可能返回NULL。无论如何,似乎想要发送电子邮件,所以我说你需要使用
mailComposer = [[MFMailComposeViewController alloc] init];