23

我有一个简单的应用程序,它打开一个模式视图来发送电子邮件。我正在使用 Xcode 4.2 和 iOS 5,并且正在使用 iOS 模拟器进行测试。由于未捕获的异常“NSInvalidArgumentException”,应用程序崩溃并 终止应用程序,原因:
“应用程序试图在目标上呈现一个 nil 模态视图控制器。”

执行该行时:

 [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];
}
...
...

请问有什么指点吗?

4

2 回答 2

57

我也遇到过类似的问题。我分配了一个实例MFMailComposeViewController并尝试以模态方式呈现它。我也有一个例外:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target

这是因为邮件选项在 iPhone 的设置中被禁用。当设备中未设置邮件帐户时,也可能出现这种情况。所以MFMailCompseViewController实例将是nil并且以模态方式呈现它会导致崩溃。

我使用的canSendMail方法MFMailComposeViewController来解决这个问题。

Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil) {
    MFMailComposeViewController * mailView = [[MFMailComposeViewController alloc] init];
    mailView.mailComposeDelegate = self;

    //Set the subject
    [mailView setSubject:emailSubject];

    //Set the mail body
    [mailView setMessageBody:emailBody isHTML:YES];


    //Display Email Composer
    if([mailClass canSendMail]) {
        [self.navControl presentModalViewController:mailView animated:YES];
    }
}
于 2012-06-05T05:29:52.437 回答
15
 mailComposer = [[MFMessageComposeViewController alloc] init];

在我看来,是问题的根源。模拟器无法发送 SMS 消息,因此初始化方法可能返回 NULL。无论如何,sou 似乎想发送电子邮件,所以我说你需要使用

 mailComposer = [[MFMailComposeViewController alloc] init];
于 2012-05-03T16:35:28.040 回答