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

1

5

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>.'
Thyself answered 6/2, 2016 at 19:25 Comment(0)
W
12

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)
}
Wanhsien answered 6/2, 2016 at 19:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.