Application tried to present a nil modal view controller on target 問題

MFMailComposeViewController を使ってメール送信ダイアログを表示しようとしたところ、Application tried to present a nil modal view controller on target が発生してアプリが強制終了されてしまう問題に遭遇。

iphone – 'Application tried to present a nil modal view controller on target' error/crash when trying to open mail composer – Stack Overflow

に書いてあるとおり、MFMailComposeViewController の canSendMail を使って、端末からメールを送れる状態であるかを確認する必要がある。
テスト用端末や Simulator だとメールの設定をしていないことも多いと思うので、遭遇することがありそうだ。

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

ちなみに、メールを送信できない環境である場合自動的にダイアログが表示される。

Mfmail

さらにちなみに、SMSを送りたい場合は MFMessageComposeViewController を使い、その場合送信可能かどうかは canSendText を使うとのこと。
上記のStack Overflow の質問では、メールを送信したいのにこちらが使われていたので、二重に間違っていたことになる。

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.