Envío de SMS en iOS con Swift

En primer lugar, estoy realmente sorprendido de que esto no sea un duplicado, porque hay TONELADAS de preguntas de overflow que solucionan esto en Objective-C, pero aún tengo que ver una buena respuesta que usó Swift.

Lo que estoy buscando es un fragment de código en Swift que envíe una cadena arbitraria como el cuerpo de un post de text a un número de teléfono dado. Esencialmente, me gustaría algo parecido a esto en la documentation oficial de Apple, pero en Swift en lugar de Objective-C.

Me imagino que esto no es demasiado difícil, ya que se puede hacer en un par de líneas de código en Android.

EDITAR: Lo que estoy buscando es 5-20 líneas de código Swift, no estoy de acuerdo con que esto sea demasiado amplio. En Java (para Android), la solución se ve así:

package com.company.appname; import android.app.Activity; import android.telephony.SmsManager; public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); public static final mPhoneNumber = "1111111111"; public static final mMessage = "hello phone"; SmsManager.getDefault().sendTextMessage(mPhoneNumber, null, mMessage, null, null); } } 

Ahora esta es la solución para Android, y son solo 11 líneas. Java tiende a ser mucho más detallado que Swift, por lo que dudo que lo que pregunto sea "demasiado amplio", es más probable que no sepa cómo usar Objective-C MessageComposer porque la documentation que he vinculado A lo anterior no está claro con respecto al uso en Swift.

No estoy seguro si realmente obtuviste la respuesta. Estaba en una búsqueda similar y encontré esta solución y la puse a funcionar.

 import UIKit import MessageUI class ViewController: UIViewController, MFMessageComposeViewControllerDelegate { @IBOutlet weak var phoneNumber: UITextField! override func viewDidLoad() { super.viewDidLoad() } @IBAction func sendText(sender: UIButton) { if (MFMessageComposeViewController.canSendText()) { let controller = MFMessageComposeViewController() controller.body = "Message Body" controller.recipients = [phoneNumber.text] controller.messageComposeDelegate = self self.presentViewController(controller, animated: true, completion: nil) } } func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { //... handle sms screen actions self.dismissViewControllerAnimated(true, completion: nil) } override func viewWillDisappear(animated: Bool) { self.navigationController?.navigationBarHidden = false } } 

Solución Swift 3.0:

 func sendSMSText(phoneNumber: String) { if (MFMessageComposeViewController.canSendText()) { let controller = MFMessageComposeViewController() controller.body = "" controller.recipients = [phoneNumber] controller.messageComposeDelegate = self self.present(controller, animated: true, completion: nil) } } func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { //... handle sms screen actions self.dismiss(animated: true, completion: nil) } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = false } 

Swift 3

 @IBAction func sendSmsClick(_ sender: AnyObject) { let messageVC = MFMessageComposeViewController() messageVC.body = "Enter a message"; messageVC.recipients = ["Enter tel-nr"] messageVC.messageComposeDelegate = self; self.present(messageVC, animated: false, completion: nil) } func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { switch (result.rawValue) { case MessageComposeResult.cancelled.rawValue: print("Message was cancelled") self.dismiss(animated: true, completion: nil) case MessageComposeResult.failed.rawValue: print("Message failed") self.dismiss(animated: true, completion: nil) case MessageComposeResult.sent.rawValue: print("Message was sent") self.dismiss(animated: true, completion: nil) default: break; } } 

Si no quiere depender de un UIViewController, sigue una solución Swift 3.0 :

 import UIKit import MessageUI class ECMMessageComposerBuilder: NSObject { private dynamic var customWindow: UIWindow? private var body: String? private var phoneNumber: String? fileprivate var messageController: MFMessageComposeViewController? var canCompose: Bool { return MFMessageComposeViewController.canSendText() } func body(_ body: String?) -> ECMMessageComposerBuilder { self.body = body return self } func phoneNumber(_ phone: String?) -> ECMMessageComposerBuilder { self.phoneNumber = phone return self } func build() -> UIViewController? { guard canCompose else { return nil } messageController = MFMessageComposeViewController() messageController?.body = body if let phone = phoneNumber { messageController?.recipients = [phone] } messageController?.messageComposeDelegate = self return messageController } func show() { customWindow = UIWindow(frame: UIScreen.main.bounds) customWindow?.rootViewController = MNViewController() // Move it to the top let topWindow = UIApplication.shanetworking.windows.last customWindow?.windowLevel = (topWindow?.windowLevel ?? 0) + 1 // and present it customWindow?.makeKeyAndVisible() if let messageController = build() { customWindow?.rootViewController?.present(messageController, animated: true, completion: nil) } } func hide(animated: Bool = true) { messageController?.dismiss(animated: animated, completion: nil) messageController = nil customWindow?.isHidden = true customWindow = nil } } extension ECMMessageComposerBuilder: MFMessageComposeViewControllerDelegate { func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { controller.dismiss(animated: true, completion: nil) hide() } } 

Llamas al compositor de esta manera:

 let phoneNumber = "987654321" let composer = MNMessageComposerBuilder() composer.phoneNumber(phoneNumber).show() 

o usando una varita perezosa

 let phoneNumber = "987654321" private lazy var messageComposer: MNMessageComposerBuilder = { let composer = MNMessageComposerBuilder() return composer }() messageComposer.phoneNumber(phoneNumber).show() 
 @IBAction func sendMessageBtnClicked(sender: AnyObject) { var messageVC = MFMessageComposeViewController() messageVC.body = "Enter a message"; messageVC.recipients = ["Enter tel-nr"] messageVC.messageComposeDelegate = self; self.presentViewController(messageVC, animated: false, completion: nil) } func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { switch (result.value) { case MessageComposeResultCancelled.value: println("Message was cancelled") self.dismissViewControllerAnimated(true, completion: nil) case MessageComposeResultFailed.value: println("Message failed") self.dismissViewControllerAnimated(true, completion: nil) case MessageComposeResultSent.value: println("Message was sent") self.dismissViewControllerAnimated(true, completion: nil) default: break; } }