公司項目中要用到點擊按鈕發(fā)短信的功能,由于之前沒做過,在網(wǎng)上找了一些 demo, 自己總結(jié)點,大神勿噴 -
**要實現(xiàn)發(fā)短信的功能其實不難,可以利用系統(tǒng)的MessageUI.framework框架 **就可以實現(xiàn),步驟如下:
1.首先判斷設(shè)備是否有發(fā)送短信功能
?。?如果設(shè)備允許發(fā)送短信,創(chuàng)建一個MFMessageComposeViewController視圖控制器,并對其設(shè)置短信內(nèi)容和收件人號碼列表。
?。?短信發(fā)送后,會執(zhí)行回調(diào)代理方法,可以獲取發(fā)送結(jié)果(成功,失敗或取消)
代碼如下:
import UIKit
//導(dǎo)入頭文件
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?) {
//設(shè)置聯(lián)系人
let str = "10086"
//創(chuàng)建一個彈出框提示用戶
let alertController = UIAlertController(title: "發(fā)短信", message: "是否給\(str)發(fā)送短信?", preferredStyle: .alert)
let cancleAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let sendAction = UIAlertAction(title: "確定", style: .default) { (alertController) in
//判斷設(shè)備是否能發(fā)短信(真機還是模擬器)
if MFMessageComposeViewController.canSendText() {
let controller = MFMessageComposeViewController()
//短信的內(nèi)容,可以不設(shè)置
controller.body = "發(fā)短信"
//聯(lián)系人列表
controller.recipients = [str]
//設(shè)置代理
controller.messageComposeDelegate = self
self.present(controller, animated: true, completion: nil)
} else {
print("本設(shè)備不能發(fā)短信")
}
}
alertController.addAction(cancleAction)
alertController.addAction(sendAction)
self.present(alertController, animated: true, completion: nil)
}
//實現(xiàn)MFMessageComposeViewControllerDelegate的代理方法
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
controller.dismiss(animated: true, completion: nil)
//判斷短信的狀態(tài)
switch result{
case .sent:
print("短信已發(fā)送")
case .cancelled:
print("短信取消發(fā)送")
case .failed:
print("短信發(fā)送失敗")
default:
print("短信已發(fā)送")
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
這樣一個簡單的發(fā)短信的功能就實現(xiàn)了,基本上夠用了