在 App 裡放一顆電話按鈕是很常見的需求。看似簡單,但三種實作在「撥號後的使用者體驗」與「能否通過審核」上差很多,值得先比較再選。
NSString *num = [NSString stringWithFormat:@"tel://%@", number]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];
直接進入撥號流程。缺點是通話結束後使用者會被留在電話 App(進入聯絡人列表),不會自動回到你的 App,流程被打斷。
NSString *num = [NSString stringWithFormat:@"telprompt://%@", number]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];
差別在於撥號前會先跳一個確認框,通話結束後能自動跳回 App,體驗明顯更好。但要注意:這個 scheme 屬於非公開行為,網路上普遍流傳它可能導致審核被拒,正式上線前請自行確認當前的審核政策,不要只憑舊文章就當成安全方案。
這是三者中最穩妥的折衷:使用一個不加入畫面的離線 UIWebView,載入 tel: 連結即可。
- (void)callPhone {
NSString *phoneNum = @"";
NSURL *phoneURL = [NSURL URLWithString:
[NSString stringWithFormat:@"tel:%@", phoneNum]];
if (!phoneCallWebView) {
phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
// 這個 webView 只作為後端載體,不需要 addSubview
}
[phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
}
UIButton *btnPhone = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnPhone.frame = CGRectMake(280, 10, 30, 30);
btnPhone.backgroundColor = [UIColor redColor];
[btnPhone addTarget:self
action:@selector(callAction)
forControlEvents:UIControlEventTouchUpInside];
[self.window addSubview:btnPhone];
另外提醒:以上 UIWebView 與手动 addSubview 到 window 的寫法都屬於較早期的 API 習慣。若你在維護新專案,建議改用 WKWebView,並以 UIViewController 的 view hierarchy 來掛載按鈕,而不要直接操作 window。