萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 呼叫系統 App:地圖、電話、郵件、簡訊、瀏覽器完整範例

使用 UIApplication openURL 呼叫系統應用

iOS 透過 URL Scheme 啟動對應系統 App,核心 API:
UIApplication.shared.open(url, options: [:], completionHandler: nil)(iOS 10+)。

常用 URL Scheme 速查

功能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)
}

進階:MessageUI 框架在 App 內撰寫郵件/簡訊

若需在 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)
    }
}

注意事項

  • 電話/簡訊/郵件 Scheme 在模擬器無效,需真機測試。
  • open(_:options:completionHandler:) 為非同步,完成回調可處理成功/失敗。
  • iOS 10 以前用 openURL(_:)(已棄用)。
  • 自訂 URL Scheme 需在 Info.plist LSApplicationQueriesSchemes 白名單宣告才能用 canOpenURL 檢測。

善用系統 App 整合,減少自建功能成本,提升使用者熟悉度與信任感。

copyright © 萬盛學電腦網 all rights reserved