iOS Developer

Swift3.0 中实现发短信功能

2017-03-30  本文已影响0人  YANG1220

公司项目中要用到点击按钮发短信的功能,由于之前没做过,在网上找了一些 demo, 自己总结点,大神勿喷 -

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

import UIKit
//导入头文件
import MessageUI

//遵守代理 - MFMessageComposeViewControllerDelegate
class ViewController: UIViewController , UINavigationControllerDelegate, MFMessageComposeViewControllerDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
      self.view.backgroundColor = UIColor.lightGray
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      //设置联系人
        let str = "10086"
      //创建一个弹出框提示用户
        let alertController = UIAlertController(title: "发短信", message: "是否给\(str)发送短信?", preferredStyle: .alert)
        let cancleAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let sendAction = UIAlertAction(title: "确定", style: .default) { (alertController) in
            //判断设备是否能发短信(真机还是模拟器)
            if MFMessageComposeViewController.canSendText() {
                let controller = MFMessageComposeViewController()
                //短信的内容,可以不设置
                controller.body = "发短信"
                //联系人列表
                controller.recipients = [str]
                //设置代理
                controller.messageComposeDelegate = self
                self.present(controller, animated: true, completion: nil)
            } else {
                print("本设备不能发短信")
            }
        }
        alertController.addAction(cancleAction)
        alertController.addAction(sendAction)
        
        self.present(alertController, animated: true, completion: nil)
        
    }
    //实现MFMessageComposeViewControllerDelegate的代理方法
    func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
        controller.dismiss(animated: true, completion: nil)
        //判断短信的状态
        switch result{

        case .sent:
            print("短信已发送")
        case .cancelled:
            print("短信取消发送")
        case .failed:
            print("短信发送失败")
        default:
            print("短信已发送")
            break
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

这样一个简单的发短信的功能就实现了,基本上够用了

上一篇下一篇

猜你喜欢

热点阅读