標籤:c代碼 pen ons 9.1 available phone 系統版本 handle oat
模擬器在撥打到電話方法不執行,必須真機才能撥打到電話。一下方法是在iOS10系統下進行測試
方法一、requestWithURL (推薦使用)
特點: 撥打前彈出提示。 並且, 撥打完以後會回到原來的應用。
OC代碼:
NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"10086"];UIWebView * callWebview = [[UIWebView alloc] init];[callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];[self.view addSubview:callWebview];
Swift代碼:
let callWebview = UIWebView()callWebview.loadRequest(NSURLRequest(url: URL(string: "tel:10086")!) as URLRequest)self.view.addSubview(callWebview)
方法二、openURL(telprompt)
特點: 撥打前彈出提示。 並且, 撥打完以後會回到原來的應用。網上說這個方法可能不合法 無法通過審核
OC代碼:
NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt:%@",@"10086"];[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
Swift代碼:
UIApplication.shared.openURL(URL(string: "telprompt:10086")!)
方法三、利用openURL(tel)
特點: 撥打前無彈出提示。 並且, 撥打完以後會回到原來的應用。此方法網上有文章說,撥打完電話留在通訊錄,不會回到原來應用,可能是iOS10之前的系統,我用iOS10系統測試確實回到了原來的應用。
OC代碼:
NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"10086"];[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
Swift代碼:
UIApplication.shared.openURL(URL(string: "tel:10086")!)
Xcode8開發工具下使用- (BOOL)openURL:(NSURL*)url
會有如下警告!
Please use openURL:options:completionHandler: instead
iOS10 API改動:
- (BOOL)openURL:(NSURL*)url;//不提倡使用
iOS10之後建議改用下邊的API替換
- (void)openURL:(NSURL*)url options:(NSDictionary<NSString *, id> *)options completionHandler:(void (^ __nullable)(BOOL success))completion;
備忘:
1.在iOS10之後再用openURL:
的方法撥打到電話會有1-2秒的延遲時間,iOS10之後使用openURL: options: completionHandler:
的API可以解決延遲問題。
2.此openURL: options: completionHandler:
方法API在iOS11下測試情況:撥打前彈出提示, and, 撥打完以後會回到原來的應用。
例如:
OC代碼:
NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@",@"10086"];CGFloat version = [[[UIDevice currentDevice]systemVersion]floatValue]; if (version >= 10.0) { /// 大於等於10.0系統使用此openURL方法 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil]; } else { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]]; }
OC代碼中,判斷系統方法可以換成下邊的語句(其實是Xcode9.1自動提示添加),這樣的話,就不用自己取系統版本號碼了,而是用了系統方法@available(iOS 10.0, *)
,代碼如下:
NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", @"10086"]; if (@available(iOS 10.0, *)) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil]; } else { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]]; }
Swift3 代碼:
let tel = "10086"if #available(iOS 10.0, *) { UIApplication.shared.open(URL(string: "tel:" + tel!)!, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(URL(string: "tel:" + tel!)!) }
iOS -- 撥打到電話