iOS dial a phone call 在app內撥電話

iOS上面並沒有直接呼叫撥號功能的方式,必須透過UIWebView來進行(iOS 3.1後,iOS 3.1前是使用UIApplication),也就是用URL的方式進行撥號,根據官方文件“Mail Links”、“Phone Links”、“Text Links”、“Map Links”、“YouTube Links”、“iTunes Links”等的東西都可以透過url來呼叫,以下就先介紹撥號。

撥號的URL格式為:"tel:1234567890"
如果需要加上#字號 ex:"tel:1234567890#123",請將"#"換為"p" ex:"tel:1234567890p123"
需要二次撥號加上"," ex:"tel:1234567890,123"

NSURL *phoneNumber = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"tel:123456789"]];
if ( [[UIApplication sharedApplication] canOpenURL: phoneNumber] ){
//get iOS version
NSString *osVersion = [[UIDevice currentDevice] systemVersion];
//NSLog(@"iOS version = %@",osVersion);

if ([osVersion floatValue] >= 3.1) {
NSLog(@"iOS version is after 3.1, version = %@",osVersion);
UIWebView *webview = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
webview.alpha = 0.0;
NSLog(@"phoneNumber = %@",phoneNumber);
[webview loadRequest:[NSURLRequest requestWithURL:phoneNumber]];

// Assume we are in a view controller and have access to self.view
[self.view addSubview:webview];
[webview release];

}
else {
// On 3.0 and below, dial as usual
NSLog(@"iOS version is below 3.1, version = %@",osVersion);
[[UIApplication sharedApplication] openURL: phoneNumber];
}
}else{
//can not get phone call
UIAlertView* alert = [[UIAlertView alloc] initWithTitle: @"系統訊息"
message: @"無法順利撥號"
delegate: nil
cancelButtonTitle: @"確認"
otherButtonTitles: nil];
[alert show];
[alert release];
}


撥號成功
系統會自動產生是否確定撥號的訊息


撥號失敗
我們自己寫的警告無法順利撥號


參考連結
iOS Reference Library
iOS Reference Library - Apple URL Scheme Reference

沒有留言:

張貼留言