iOS 透過 URL Scheme 啟動對應系統 App,核心 API:UIApplication.shared.open(url, options: [:], completionHandler: nil)(iOS 10+)。
| 功能 | Scheme 格式 | 範例 |
|---|---|---|
| 地圖 | https://maps.apple.com/?q=查詢文字 | https://maps.apple.com/?q=1 Infinite Loop, Cupertino, CA |
| 電話 | tel://電話號碼 | tel://0800123456 |
| 簡訊 | sms://電話號碼 或 sms://號碼?body=內容 | sms://0912345678?body=Hello |
| 郵件 | mailto://email@example.com 可加 ?subject=&body= | mailto://support@example.com?subject=Feedback |
| 瀏覽器 | https://網址 | https://developer.apple.com |
| 設定頁 | app-settings:(iOS 16+) | app-settings: |
// 開啟地圖
@IBAction func openMaps() {
let address = "1 Infinite Loop, Cupertino, CA 95014"
let encoded = address.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: "https://maps.apple.com/?q=\(encoded)")!
UIApplication.shared.open(url)
}
// 發送郵件
@IBAction func openEmail() {
let url = URL(string: "mailto://devprograms@apple.com?subject=Support")!
UIApplication.shared.open(url)
}
// 撥打電話
@IBAction func openPhone() {
let url = URL(string: "tel://0800123456")!
UIApplication.shared.open(url)
}
// 發送簡訊(僅開啟 Messages App)
@IBAction func openSMS() {
let url = URL(string: "sms://0912345678")!
UIApplication.shared.open(url)
}
// 開啟網頁
@IBAction func openBrowser() {
let url = URL(string: "https://developer.apple.com")!
UIApplication.shared.open(url)
}
若需在 App 內直接編輯內容而不跳轉,使用 MFMailComposeViewController、MFMessageComposeViewController:
import MessageUI
func presentSMSComposer() {
guard MFMessageComposeViewController.canSendText() else { return }
let vc = MFMessageComposeViewController()
vc.messageComposeDelegate = self
vc.recipients = ["0912345678"]
vc.body = "預設內文"
present(vc, animated: true)
}
// 委託處理送出/取消
extension ViewController: MFMessageComposeViewControllerDelegate {
func messageComposeViewController(_ controller: MFMessageComposeViewController,
didFinishWith result: MessageComposeResult) {
controller.dismiss(animated: true)
}
}
open(_:options:completionHandler:) 為非同步,完成回調可處理成功/失敗。openURL(_:)(已棄用)。LSApplicationQueriesSchemes 白名單宣告才能用 canOpenURL 檢測。善用系統 App 整合,減少自建功能成本,提升使用者熟悉度與信任感。