最近梳理项目发现一个问题,在iOS10.2及其以后系统的手机上调用系统打电话这个方法有点不正常, 我们代码如下:
/**
呼叫客服
*/
func customerService() {
let alertView = UIAlertController(title: nil, message: CUSTOMER_SERVICE_TEL, preferredStyle: UIAlertControllerStyle.alert)
alertView.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil))
alertView.addAction(UIAlertAction(title: "呼叫", style: UIAlertActionStyle.default, handler: { (alertAction) -> Void in
let url1 = URL(string: "tel://\(CUSTOMER_SERVICE_TEL)")
UIApplication.shared.openURL(url1!)
}))
self.presentVC(alertView)
}
这样的代码在iOS10.2以下设备上运行是正常的,但是在iOS10.2及其以上就会弹出两次弹框,查过之后才发现iOS10.2及其以上系统会自动弹出这个弹框不必自己再写弹框,所以原则上只需要判断一下当前手机操作系统版本如果为10.2及其以上直接调用系统方法打电话即可,代码如下:
if #available(iOS 10.2, *) {
if let telUrl = URL(string: "tel://\(CUSTOMER_SERVICE_TEL)") {
UIApplication.shared.openURL(telUrl)
}
} else {
let alertView = UIAlertController(title: nil, message: CUSTOMER_SERVICE_TEL, preferredStyle: UIAlertControllerStyle.alert)
alertView.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil))
alertView.addAction(UIAlertAction(title: "呼叫", style: UIAlertActionStyle.default, handler: { (alertAction) -> Void in
let url1 = URL(string: "tel://\(CUSTOMER_SERVICE_TEL)")
UIApplication.shared.openURL(url1!)
}))
self.presentVC(alertView)
}
但是这样改过之后发现效果并不是自己想的那么美好,恶心的现象发生了: 由于系统自己弹出的弹框出现会有一段等待时间,不像我们自己写的Alert框那样立刻弹出,而是会隔一会才弹出响应,查阅了一下资料貌似是ios10.2以后,这东西会阻塞主线程,所以这样改就完美了:
if #available(iOS 10.2, *) {
if let telUrl = URL(string: "tel://\(CUSTOMER_SERVICE_TEL)") {
DispatchQueue.global().async {
UIApplication.shared.openURL(telUrl)
}
}
}
} else {
let alertView = UIAlertController(title: nil, message: CUSTOMER_SERVICE_TEL, preferredStyle: UIAlertControllerStyle.alert)
alertView.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil))
alertView.addAction(UIAlertAction(title: "呼叫", style: UIAlertActionStyle.default, handler: { (alertAction) -> Void in
let url1 = URL(string: "tel://\(CUSTOMER_SERVICE_TEL)")
UIApplication.shared.openURL(url1!)
}))
self.presentVC(alertView)
}