iOS+Swift: 使用MessageUI.framework发送短信

在iOS中, 可以使用MessageUI.framework框架发送短信, 步骤如下:

代码下载http://git.oschina.net/yao_yu/swift_cnblogs_samples/tree/master/Y0001_SendSMS

  1. 添加MessageUI.framework框架
  2. 为ViewController类

    • 添加UINavigationControllerDelegate, MFMessageComposeViewControllerDelegate 接口
    • 实现func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult)
  3. 发送短信很简单

    func sendSMS(){
        if MFMessageComposeViewController.canSendText(){
            let controller = MFMessageComposeViewController()
            controller.body = txtSMS.text
            controller.recipients = txtTo.text.componentsSeparatedByString(",")
            controller.messageComposeDelegate = self
            self.presentViewController(controller, animated: true, completion: nil)
        } else {
            let alert = UIAlertView(title: "提示信息", message: "本设备不能发短信", delegate: nil, cancelButtonTitle: "确定")
            alert.show()
        }
    }
    
    func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
    
        controller.dismissViewControllerAnimated(true, completion: nil)
    
        switch result.value{
        case MessageComposeResultSent.value:
            lblResult.text = "短信已发送"
        case MessageComposeResultCancelled.value:
            lblResult.text = "短信已取消"
        case MessageComposeResultFailed.value:
            lblResult.text = "短信发送失败"
        default:
            break
        }
    }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。