在 iOS 應用中,我們常看到點擊連結直接跳轉至 App Store、撥打電話、發送郵件等操作。這些第三方應用與系統應用的互動,正是透過 Apple 定義的 URL Schemes 實現。只要遵循規範,App 即可無縫呼叫系統功能,提供流暢使用者體驗。
| 應用類型 | 呼叫方法 |
|---|---|
| Native App(本地應用) | [[UIApplication sharedApplication] openURL:] |
| Web App(Safari / UIWebView) | 點擊或長按連結自動觸發 |
前提:必須提供符合規範的 URL Scheme。
使用 mailto: 協定啟動 Mail App。
<a href="mailto:frank@wwdcdemo.example.com">John Frank</a>
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!
使用 tel: 協定啟動 Phone App 撥號。
<a href="tel:1-408-555-5555">1-408-555-5555</a>
網頁點擊會彈出確認對話框;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];
}
* 或 # 時不會撥號stringByAddingPercentEscapesUsingEncoding:)<meta name="format-detection" content="telephone=no">
使用 sms: 協定啟動 Messages App。
<a href="sms:">Launch Messages App</a>
<a href="sms:1-408-555-1212">New SMS Message</a>
if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:1-408-555-1212"]]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"無法開啟程式" delegate:nil cancelButtonTitle:@"確認" otherButtonTitles:nil];
[alert show];
}
透過 iTunes Link Maker 取得連結。
<a href="https://itunes.apple.com/cn/app/numbers/id361304891?mt=8">Numbers</a>
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://maps.apple.com/?q=cupertino"]];
正確 Map 連結規則: 域名必為 maps.apple.com、路徑不為 /maps/*、參數不為 q=*、不含 view=text 或 dirflag=r。
以 https://www.youtube.com/ 開頭,非 youtube://。
<a href="https://www.youtube.com/watch?v=xNsGNlDb6xY">iPhone5</a>
<a href="https://www.youtube.com/v/xNsGNlDb6xY">iPhone5</a>
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),並對使用者輸入做適當編碼驗證。