应用程序试图在发送文本时在目标上呈现一个 nil 模态视图控制器

Application tried to present a nil modal view controller on target when sending text

我正在尝试发送一条短信并像这样设置控制器,但我收到一条错误消息'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target <Ally.TextMessageController: 0x7fd5361278e0>.'我已经确保在我的情节提要中将它连接到 TextMessageController 所以我不太确定是什么导致了崩溃。

class TextMessageController: UIViewController, MFMessageComposeViewControllerDelegate {

    var phone: String?
    override func viewDidLoad() {
        super.viewDidLoad()



        print(phone)
        var messageVC = MFMessageComposeViewController()

        messageVC.body = "Hey I need help, are you available";
        messageVC.recipients = ["555555555"]
        messageVC.messageComposeDelegate = self;

        presentViewController(messageVC, animated: false, completion: nil)

        // Do any additional setup after loading the view.
    }


    func canSendText() -> Bool {
        return MFMessageComposeViewController.canSendText()
    }

    func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {

        self.dismissViewControllerAnimated(true, completion: nil)
        switch (result.rawValue) {
        case MessageComposeResultCancelled.rawValue:
            print("Message was cancelled")
            self.dismissViewControllerAnimated(true, completion: nil)
        case MessageComposeResultFailed.rawValue:
            print("Message failed")
            self.dismissViewControllerAnimated(true, completion: nil)
        case MessageComposeResultSent.rawValue:
            print("Message was sent")
            self.dismissViewControllerAnimated(true, completion: nil)
        default:
            break;
        }
    }

这是错误信息

'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target <Ally.TextMessageController: 0x7fd5361278e0>.'

您应该先检查设备是否可以发送短信,然后才显示。例如模拟器无法发送短信,因此您的代码将在其中崩溃。与模拟器一起,用户的设备可能未设置为传递消息。所以执行以下检查

if messageVC.canSendText() {
    presentViewController(messageVC, animated: false, completion: nil)
}