Szabolcs Toth
Szabolcs Toth

Reputation: 63

Sending SMS from UITableViewController in Swift

I'd like to send SMS from my UITableViewController but the SMS window does't dismiss after sending or cancel.

import MessageUI

class TableViewController: UITableViewController, UISearchResultsUpdating {

  override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let msgVC = MFMessageComposeViewController()

    msgVC.recipients = ["555555"]

    self.presentViewController(msgVC, animated: true, completion: nil)
  }

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

    self.dismissViewControllerAnimated(true, completion: nil)

  }

}

Upvotes: 0

Views: 333

Answers (2)

zevij
zevij

Reputation: 2446

An alternative solution is to invoke the built in sms (Swift 3) on didSelect: UIApplication.shared.open(NSURL(string:"sms: number w/o spaces") as! URL)

based on this swift 2 solution or this objective-c solution (see latter part).

Upvotes: 0

rmaddy
rmaddy

Reputation: 318784

You never set the messageComposeDelegate.

import MessageUI

class TableViewController: UITableViewController, UISearchResultsUpdating, MFMessageComposeViewControllerDelegate {

  override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let msgVC = MFMessageComposeViewController()
    msgVC.messageComposeDelegate = self

    msgVC.recipients = ["555555"]

    self.presentViewController(msgVC, animated: true, completion: nil)
  }

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

    self.dismissViewControllerAnimated(true, completion: nil)

  }

}

You should also confirm that the device is setup to send messages. Please read the documentation for the MFMessageComposeViewController class. It explains all of this and shows sample code as well.

Upvotes: 4

Related Questions