iOS10 之前
头文件:
import CoreTelephony
声明一个全局的属性:
let callCenter = CTCallCenter()
//拨号
let number = "10086"
let callWebView = UIWebView()
callWebView.loadRequest(URLRequest(url:URL(string: "tel:\(number)")!))
view.addSubview(callWebView)
UIApplication.shared.open(URL(string:number)!,options: ["":""],completionHandler: nil)
//获取通话状态
callCenter.callEventHandler = { (call: CTCall) -> Void in
if call.callState == CTCallStateDisconnected {
print("电话挂断")
}
if call.callState == CTCallStateConnected {
print("电话接通")
}
if call.callState == CTCallStateIncoming {
print("通话途中收到别的来电")
}
if call.callState == CTCallStateDialing {
print("电话播出")
}
}
iOS10
头文件:
import CallKit.CXCallObserver
声明全局属性<必须的,不然代理无法监听>
let callObserver = CXCallObserver()
//拨号
let number = "10086"
let callWebView = UIWebView()
callWebView.loadRequest(URLRequest(url:URL(string: "tel:\(number)")!))
view.addSubview(callWebView)
UIApplication.shared.open(URL(string:number)!,options: ["":""],completionHandler: nil)
设置代理
callObserver.setDelegate(self,queue: DispatchQueue.main)
实现代理方法:
extension ViewController: CXCallObserverDelegate {
func callObserver(_ callObserver: CXCallObserver,callChanged call: CXCall) {
if call.isOutgoing {
print("电话播出")
if call.hasConnected {
print("电话接通")
operation(state: CurrentState.HasConnected)
}
if call.hasEnded {
print("电话挂断")
operation(state: CurrentState.HasEnded)
}
if call.isOnHold {
print("无人接听挂断")
operation(state: CurrentState.IsOnHold)
}
} else {
print("other error")
}
}
}
DEMO地址(基于Swift3.0的一个循环拨打电话的小功能的,直到接通为止)
原文链接:/swift/322132.html