萬盛學電腦網

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

iOS 開發核心技能:內建 URL Schemes 完整應用指南

什麼是 URL Schemes?

在 iOS 應用中,我們常看到點擊連結直接跳轉至 App Store、撥打電話、發送郵件等操作。這些第三方應用與系統應用的互動,正是透過 Apple 定義的 URL Schemes 實現。只要遵循規範,App 即可無縫呼叫系統功能,提供流暢使用者體驗。

兩種開啟方式

應用類型呼叫方法
Native App(本地應用)[[UIApplication sharedApplication] openURL:]
Web App(Safari / UIWebView)點擊或長按連結自動觸發

前提:必須提供符合規範的 URL Scheme。

五大類系統 URL Schemes 詳細說明

1. Mail Links(郵件)

使用 mailto: 協定啟動 Mail App。

HTML 網頁

<a href="mailto:frank@wwdcdemo.example.com">John Frank</a>

Native 程式碼

if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:frank@wwdcdemo.example.com"]]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"無法開啟程式" delegate:nil cancelButtonTitle:@"確認" otherButtonTitles:nil];
    [alert show];
}

進階參數

支援 cc、bcc、subject、body,參數值需 URL 編碼:

mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!

2. Phone Links(電話)

使用 tel: 協定啟動 Phone App 撥號。

HTML 網頁

<a href="tel:1-408-555-5555">1-408-555-5555</a>

網頁點擊會彈出確認對話框;Native 直接撥號。

Native 程式碼

if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:1-408-555-5555"]]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"無法開啟程式" delegate:nil cancelButtonTitle:@"確認" otherButtonTitles:nil];
    [alert show];
}

注意事項

  • URL 包含 * 或 # 時不會撥號
  • 使用者輸入或未知來源的號碼,特殊字元必須編碼(stringByAddingPercentEscapesUsingEncoding:)
  • Safari 預設偵測電話號碼,若頁面有類似電話的數字但非電話,可關閉偵測:
<meta name="format-detection" content="telephone=no">

3. Text Links(簡訊)

使用 sms: 協定啟動 Messages App。

HTML 網頁

<a href="sms:">Launch Messages App</a>
<a href="sms:1-408-555-1212">New SMS Message</a>

Native 程式碼

if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:1-408-555-1212"]]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"無法開啟程式" delegate:nil cancelButtonTitle:@"確認" otherButtonTitles:nil];
    [alert show];
}

4. iTunes Links(App Store / iTunes Store)

透過 iTunes Link Maker 取得連結。

HTML 網頁

<a href="https://itunes.apple.com/cn/app/numbers/id361304891?mt=8">Numbers</a>

Native 程式碼

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://maps.apple.com/?q=cupertino"]];

正確 Map 連結規則: 域名必為 maps.apple.com、路徑不為 /maps/*、參數不為 q=*、不含 view=text 或 dirflag=r。

5. YouTube Links(影片播放)

以 https://www.youtube.com/ 開頭,非 youtube://。

HTML 網頁

<a href="https://www.youtube.com/watch?v=xNsGNlDb6xY">iPhone5</a>
<a href="https://www.youtube.com/v/xNsGNlDb6xY">iPhone5</a>

Native 程式碼

if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.youtube.com/watch?v=xNsGNlDb6xY"]]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"無法開啟程式" delegate:nil cancelButtonTitle:@"確認" otherButtonTitles:nil];
    [alert show];
}

總結

善用內建 URL Schemes,能讓 App 快速整合系統功能,減少使用者操作步驟,提升體驗品質。開發時請記得處理錯誤情況(如裝置未安裝對應 App),並對使用者輸入做適當編碼驗證。

copyright © 萬盛學電腦網 all rights reserved