Swift3.0拨打电话,获取通话状态(接通,挂断...)<CoreTelephony,CallKit.CXCallObserver>

前端之家收集整理的这篇文章主要介绍了Swift3.0拨打电话,获取通话状态(接通,挂断...)<CoreTelephony,CallKit.CXCallObserver>前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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相关文章