Swift3.0 中實現發短信功能

公司項目中要用到點擊按鈕發短信的功能,由于之前沒做過,在網上找了一些 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.
    }

}

這樣一個簡單的發短信的功能就實現了,基本上夠用了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容