iOS -- 拨打电话

模拟器在拨打电话方法不执行,必须真机才能拨打电话。一下方法是在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!)!)
    }
原文地址:https://www.cnblogs.com/mafeng/p/8434250.html