导入头文件
#import <CallKit/CXCallObserver.h>
#import <CallKit/CXCall.h>
在需要的地方调用拨打电话方法,在 openURL的回调里,实例化CXCallObserver
并设置代理,同时设置回调的队列
//拨打电话
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://10086"] options:@{} completionHandler:^(BOOL success) {
NSLog(@"%d",success);
if(!success) return ;
//设置电话代理
_callObserver = [[CXCallObserver alloc]init];
[_callObserver setDelegate:self queue:dispatch_get_main_queue()];
}];
实现CXCallObserver
的代理方法,根据 call 返回的信息 判断电话处于什么状态,根据不同状态搞不同的事情
-(void)callObserver:(CXCallObserver *)callObserver callChanged:(CXCall *)call{
NSLog(@"outgoing :%d onHold :%d hasConnected :%d hasEnded :%d",call.outgoing,call.onHold,call.hasConnected,call.hasEnded);
/** 以下为我手动测试 如有错误欢迎指出
拨通: outgoing :1 onHold :0 hasConnected :0 hasEnded :0
拒绝: outgoing :1 onHold :0 hasConnected :0 hasEnded :1
链接: outgoing :1 onHold :0 hasConnected :1 hasEnded :0
挂断: outgoing :1 onHold :0 hasConnected :1 hasEnded :1
新来电话: outgoing :0 onHold :0 hasConnected :0 hasEnded :0
保留并接听: outgoing :1 onHold :1 hasConnected :1 hasEnded :0
另一个挂掉: outgoing :0 onHold :0 hasConnected :1 hasEnded :0
保持链接: outgoing :1 onHold :0 hasConnected :1 hasEnded :1
对方挂掉: outgoing :0 onHold :0 hasConnected :1 hasEnded :1
*/
//接通
if (call.outgoing && call.hasConnected && !call.hasEnded) {
//记录当前时间
_beforeDate = [NSDate date];
}
//挂断
if (call.outgoing && call.hasConnected && call.hasEnded) {
//计算通话时长
NSDate* dat = [NSDate dateWithTimeInterval:0 sinceDate:_beforeDate];
NSTimeInterval a=[dat timeIntervalSinceNow];
NSString *timeString = [NSString stringWithFormat:@"%0.f",fabs(a)];//转为字符型
NSLog(@"%@秒",timeString);
}
}
防止意外,在控制器销毁时 把 delegate 设为 nil
-(void)dealloc{
[_callObserver setDelegate:nil queue:dispatch_get_main_queue()];
_callObserver = nil;
}
注意:
如果代理回调没有执行
1.查看是否设置代理
2.需要把callObserver
全局引用,保证不销毁.
3.以上方法为10.0之后 需要判断 版本再10.0之前使用
//获取通话状态
_callCenter.callEventHandler = { (call: CTCall) -> Void in
if call.callState == CTCallStateDisconnected {
print("挂断电话")
self.callStateDisconnected()
}
if call.callState == CTCallStateConnected {
print("电话接通")
self.beforeDate = NSDate()
}
if call.callState == CTCallStateIncoming {
print("通话途中收到别的来电")
}
if call.callState == CTCallStateDialing {
print("电话播出")
}