Simone Aslan Simone Aslan - 21 days ago 9
iOS Question

Swift Code to Send Message Not Working

I am just learning to code and I am trying to create a simple code to send a message on IOS. I have made sure to import the MessageUI framework. When I run it on my simulator, it fails and shows THREAD 1 : SIGNAL SIGABRT. I apologize profusely if it's just a small mistake, as I often do such errors and don't wish to waste anyone's time. Here is my code:

import UIKit
import MessageUI


class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {



@IBOutlet weak var messageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}
@IBAction func SendSMS(sender: AnyObject) {
let messageVC = MFMessageComposeViewController()

messageVC.recipients = ["5146276051"]
messageVC.body = messageLabel.text
messageVC.messageComposeDelegate = self
self.presentViewController(messageVC, animated: true, completion: nil)


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

switch (result.rawValue) {

case MessageComposeResultCancelled.rawValue:
print("Message was cancelled")
self.dismissViewControllerAnimated(true, completion: nil)

case MessageComposeResultFailed.rawValue:
print("Message has failed")
self.dismissViewControllerAnimated(true, completion: nil)

case MessageComposeResultSent.rawValue:
print("Message was sent")
self.dismissViewControllerAnimated(true, completion: nil)

default:
break
}
}

}


Thank you very much!

Answer

Hi try to use your code on physical device, it should work.

BTW in your code please add check whether device support sending messages:

        @IBAction func SendSMS(sender: AnyObject) {
            //Checking whether device support message sending
            if (MFMessageComposeViewController.canSendText() == false) { return }

            let messageVC = MFMessageComposeViewController()

            messageVC.recipients = ["5146276051"]
            messageVC.body = messageLabel.text
            messageVC.messageComposeDelegate =  self
            self.presentViewController(messageVC, animated: true, completion: nil)
        }

in that way you will avoid e.g. crashes on simulator.

Comments