Swift - 实现发送短信的功能

使用MessageUI.framework框架可以实现短信发送功能,步骤如下:
(1)首先判断设备是否有发送短信功能
(2)如果设备允许发送短信,创建一个MFMessageComposeViewController视图控制器,并对其设置短信内容和收件人号码列表。
(3)短信发送后,会执行回调代理方法,可以获取发送结果(成功,失败或取消)
代码如下:

import UIKit
import MessageUI

class ViewController: UIViewController ,UINavigationControllerDelegate,
MFMessageComposeViewControllerDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //首先要判断设备具不具备发送短信功能
        if MFMessageComposeViewController.canSendText(){
            let controller = MFMessageComposeViewController()
            //设置短信内容
            controller.body = "短信内容:欢迎来到hangge.com"
            //设置收件人列表
            controller.recipients = ["123456","120000"]
            //设置代理
            controller.messageComposeDelegate = self
            //打开界面
            self.presentViewController(controller, animated: true, completion: { () -> Void in

            })
        }
        else{
            print("本设备不能发送短信")
        }
    }

    //发送短信代理
    func messageComposeViewController(controller: MFMessageComposeViewController,
        didFinishWithResult result: MessageComposeResult) {
            controller.dismissViewControllerAnimated(true, completion: nil)
            switch result.rawValue{
                case MessageComposeResultSent.rawValue:
                    print("短信已发送")
                case MessageComposeResultCancelled.rawValue:
                    print("短信取消发送")
                case MessageComposeResultFailed.rawValue:
                    print("短信发送失败")
                default:
                    break
            }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

你可能感兴趣的:(swift,短信)