Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to sent a text message and have controller set up like so, but I get an error message 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target <Ally.TextMessageController: 0x7fd5361278e0>.' I've made sure that in my storyboard I'm connecting it to TextMessageController so I'm not quite sure what is causing the crash.

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

Here is the error message

'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target <Ally.TextMessageController: 0x7fd5361278e0>.'
like image 772
Rafa Avatar asked Dec 14 '22 08:12

Rafa


1 Answers

You should first check whether device can send the text message and then only present it. For instance simulator can not send text message thus your code will crash in it. Along with simulator, user’s device may not be set up for the delivery of messages. So perform following check

if messageVC.canSendText() {
    presentViewController(messageVC, animated: false, completion: nil)
}
like image 61
Vishnu gondlekar Avatar answered May 22 '23 04:05

Vishnu gondlekar