ในบทช่วยสอนนี้จะสอนวิธีส่งข้อความ SMS จากแอป iOS ด้วย Swift โดยใช้หมายเลขโทรศัพท์ของผู้ใช้ แม้จะไม่สามารถส่งโดยตรงโดยไม่ผ่านการยืนยันของผู้ใช้ แต่สามารถแสดงข้อความสำเร็จรูปให้ผู้ใช้แก้ไขและส่งต่อได้
เราจะใช้คลาส MFMessageComposeViewController เพื่อแสดงอินเตอร์เฟสการเขียนข้อความมาตรฐานภายในแอป
ก่อนแสดงอินเตอร์เฟส จะกำหนดข้อความต้นฉบับและรายชื่อผู้รับล่วงหน้า ซึ่งผู้ใช้สามารถแก้ไขได้ในภายหลัง อินเตอร์เฟสนี้ไม่รับประกันการส่งสำเร็จ แค่ช่วยสร้างข้อความและแสดงให้ผู้ใช้อนุมัติเท่านั้น ผู้ใช้สามารถยกเลิกได้ (ข้อความจะถูกทิ้ง) หรือกดส่ง (แอป Messages จะดูแลการส่งต่อ)
ขั้นตอนที่ 1: สร้างโปรเจกต์
เปิด Xcode → New Project → Single View Application → ตั้งชื่อว่า "MailComposer"
ขั้นตอนที่ 2: ออกแบบ UI
เปิด Main.storyboard เพิ่มปุ่ม ตั้งชื่อ "Send Mail" เพิ่ม Constraints "Horizontally and Vertically in container" และ "width = 100 points, height = 50 points"


ขั้นตอนที่ 3: สร้าง IBAction
ไปที่ ViewController.swift สร้าง @IBAction ของปุ่ม ชื่อ "sendMessage"
@IBAction func sendMessage(_ sender: Any) { }ขั้นตอนที่ 4: เพิ่ม Protocol และ Import
เพิ่ม MFMessageComposeViewControllerDelegate protocol ให้ ViewController และเพิ่ม stub method Import MessageUI ใน ViewController.swift
ขั้นตอนที่ 5: สร้างเมธอดแสดงอินเตอร์เฟส
สร้างเมธอด displayMsgInterface ใต้ viewDidLoad
func displayMsgInterface() {
let messageCompose = MFMessageComposeViewController()
messageCompose.messageComposeDelegate = self
// กำหนดผู้รับ
messageCompose.recipients = ["9401234567"]
// กำหนดเนื้อหาข้อความ
messageCompose.body = "Hey! I just learned how to send message using iOS App."
// แสดงแบบ Modal
if MFMessageComposeViewController.canSendText() {
self.present(messageCompose, animated: true, completion: nil)
} else {
print("You cannot send messages.")
}
}ขั้นตอนที่ 6: เพิ่ม Delegate Method
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
self.dismiss(animated: true, completion: nil)
}ขั้นตอนที่ 7: เรียกใช้เมธอด
เรียก displayMsgInterface() จาก viewDidLoad
โค้ดเต็มรูปแบบ:

ทดสอบ
ต้องรันบนอุปกรณ์จริง เนื่องจาก Simulator ไม่รองรับการส่ง SMS

