在 iOS 中要跳出自己的 App 去撥號、寫信或開網頁,最輕量的做法就是利用 UIApplication 的 openURL:,把一組自訂 scheme 的 URL 交給系統,由系統決定該喚起哪個內建應用。下面把常用的幾種情境整理成一份可直接複製的清單。
使用 mailto:// 前綴即可開啟預設的郵件撰寫畫面:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://admin@hzlzh.com"]];
最直覺的寫法是用 tel:// 或 tel: 搭配號碼:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://8008808888"]];
這種方式會直接切換到電話 App,使用者按結束通話後畫面會停留在通話紀錄,不會自動回到你的 App。若希望通話結束後能回到原本的操作流程,可以改用 UIWebView 來觸發撥號:
UIWebView *callWebview = [[UIWebView alloc] init];
NSURL *telURL = [NSURL URLWithString:@"tel:10086"]; // tel:// 與 tel: 皆可
[callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
[self.view addSubview:callWebview]; // 記得加入檢視階層
另外還有一種私有 scheme telprompt://,撥完會自動跳回 App,但屬於非公開 API,提交審核有風險:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://10086"]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://800888"]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.hzlzh.com"]];
sms:// 只能指定收件者號碼,無法預填本文。若需要同時帶入內容與多位收件人,就得改用 MessageUI 框架:
MessageUI.framework#import <MessageUI/MFMessageComposeViewController.h>MFMessageComposeViewControllerDelegate核心程式碼如下:
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
MFMessageComposeViewController *controller =
[[[MFMessageComposeViewController alloc] init] autorelease];
if ([MFMessageComposeViewController canSendText])
{
controller.body = bodyOfMessage;
controller.recipients = recipients;
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
didFinishWithResult:(MessageComposeResult)result
{
[self dismissModalViewControllerAnimated:YES];
if (result == MessageComposeResultCancelled)
NSLog(@"Message cancelled");
else if (result == MessageComposeResultSent)
NSLog(@"Message sent");
else
NSLog(@"Message failed");
}
小提醒:簡訊編輯畫面預設顯示英文,若要在 .xib 中補上一組 Chinese 的 Localization,介面就會跟著系統語言走。
實務上還要注意:模擬器無法真正撥號,且 canSendText 在缺少 SIM 卡或裝置不支援時會回傳 NO,記得先判斷再呼叫,避免流程中斷。