在 App 中加入撥號功能相當實用,以下整理三種常見做法。
- (void)callAction {
NSString *number = @""; // 此處讀入電話號碼
// NSString *num = [[NSString alloc] initWithFormat:@"tel://%@", number];
// 使用 tel:// 結束通話後會進入聯絡人列表
// 使用 telprompt:// 會先彈出是否撥號的確認框,撥完後回到 App
// 注意:此方法可能不被接受,無法通過審核
NSString *num = [[NSString alloc] initWithFormat:@"telprompt://%@", number];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]]; // 撥號
}
// 加入電話圖示按鈕 UIButton *btnPhone = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; btnPhone.frame = CGRectMake(280, 10, 30, 30); [btnPhone setBackgroundColor:[UIColor redColor]]; // 點擊直接撥號 [btnPhone addTarget:self action:@selector(callAction) forControlEvents:UIControlEventTouchUpInside]; [self.window addSubview:btnPhone];
-(void)CallPhone {
NSString *phoneNum = @""; // 電話號碼
NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", phoneNum]];
if (!phoneCallWebView) {
// 這個 webView 只是後台載入用途,不需 add 到畫面上
// 效果與方式二相同,但這種做法合法
phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
}
[phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
}
三種方式各有取捨:telprompt:// 會先彈出確認框並在通話後回到 App,但存在審核風險;使用隱藏的 UIWebView 載入 tel: 則是較安全、可通過審核的做法。實際開發時建議採用方式三。