Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách gửi tin nhắn SMS từ ứng dụng iOS bằng Swift

Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách gửi tin nhắn từ ứng dụng iOS bằng Swift, sử dụng số điện thoại của người dùng. Mặc dù không thể gửi trực tiếp mà không có sự đồng ý, nhưng chúng ta có thể hiển thị giao diện soạn tin nhắn đã soạn sẵn để người dùng xem lại và gửi.

Sử dụng MFMessageComposeViewController

Lớp MFMessageComposeViewController cung cấp giao diện soạn tin nhắn chuẩn của hệ thống bên trong ứng dụng của bạn.

Lưu ý quan trọng: Giao diện này không đảm bảo việc gửi tin nhắn thành công, nó chỉ xây dựng tin nhắn ban đầu và hiển thị để người dùng phê duyệt. Người dùng có thể hủy bỏ, khi đó tin nhắn bị hủy. Nếu chọn gửi, ứng dụng Messages của hệ thống sẽ chịu trách nhiệm gửi tin nhắn.

Các bước thực hiện

Bước 1: Tạo dự án

Xcode → New Project → Single View App → Tên: "MailComposer" (tên gợi ý, thực chất là SMS Composer).

Bước 2: Thiết lập Storyboard

Mở Main.storyboard → Thêm 1 Button, đặt tên "Send Message" → Thêm constraints: Horizontally & Vertically in Container, Width = 100, Height = 50.

Cách gửi tin nhắn SMS từ ứng dụng iOS bằng Swift

Cách gửi tin nhắn SMS từ ứng dụng iOS bằng Swift

Bước 3: Tạo IBAction

Mở ViewController.swift → Tạo @IBAction cho button, đặt tên sendMessage:

@IBAction func sendMessage(_ sender: Any) { }

Bước 4: Cấu hình Delegate và Import Framework

  • Thêm protocol MFMessageComposeViewControllerDelegate cho class ViewController
  • Import MessageUI vào ViewController.swift
  • Thêm stub method để tuân thủ protocol

Bước 5: Tạo phương thức hiển thị giao diện soạn tin

Tạo method displayMsgInterface() dưới viewDidLoad:

func displayMsgInterface() {
    let messageCompose = MFMessageComposeViewController()
    messageCompose.messageComposeDelegate = self
    
    // Cấu hình người nhận
    messageCompose.recipients = ["09401234567"]
    
    // Cấu hình nội dung tin nhắn
    messageCompose.body = "Hey! I just learned how to send message using iOS App."
    
    // Hiển thị modal nếu thiết bị hỗ trợ gửi tin nhắn
    if MFMessageComposeViewController.canSendText() {
        self.present(messageCompose, animated: true, completion: nil)
    } else {
        print("Thiết bị này không thể gửi tin nhắn.")
    }
}

Bước 6: Xử lý delegate khi kết thúc

func messageComposeViewController(_ controller: MFMessageComposeViewController, 
                                   didFinishWith result: MessageComposeResult) {
    self.dismiss(animated: true, completion: nil)
}

Bước 7: Gọi phương thức

Gọi displayMsgInterface() trong viewDidLoad hoặc trong sendMessage action.

Mã hoàn chỉnh

import UIKit
import MessageUI

class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // self.displayMsgInterface() // Gọi ở đây hoặc trong action
    }
    
    @IBAction func sendMessage(_ sender: Any) {
        displayMsgInterface()
    }
    
    func displayMsgInterface() {
        let messageCompose = MFMessageComposeViewController()
        messageCompose.messageComposeDelegate = self
        messageCompose.recipients = ["09401234567"]
        messageCompose.body = "Hey! I just learned how to send message using iOS App."
        
        if MFMessageComposeViewController.canSendText() {
            self.present(messageCompose, animated: true, completion: nil)
        } else {
            print("Thiết bị này không thể gửi tin nhắn.")
        }
    }
    
    func messageComposeViewController(_ controller: MFMessageComposeViewController, 
                                       didFinishWith result: MessageComposeResult) {
        self.dismiss(animated: true, completion: nil)
    }
}

Lưu ý quan trọng

  • Chỉ chạy trên thiết bị thật - Simulator không hỗ trợ gửi tin nhắn
  • Cần thêm key NSMessageCompositionUsageDescription vào Info.plist (iOS 10+)
  • Số điện thoại trong recipients chỉ là gợi ý, người dùng có thể thay đổi

Cách gửi tin nhắn SMS từ ứng dụng iOS bằng Swift

Cách gửi tin nhắn SMS từ ứng dụng iOS bằng Swift

Cách gửi tin nhắn SMS từ ứng dụng iOS bằng Swift