iOS监听电话来电、挂断、拨号等

以下,来讲解在app内如何调用打电话功能和监听电话来电、挂断、拨号等功能。

简单的UI布局:

首先,先实现拨打电话的功能,以便于后续测试:

// 拨打电话
- (IBAction)dialingButtonClick:(UIButton *)sender {
    NSURL *url = [NSURL URLWithString:@"tel:138xxxxxxxx"];// 填入有效电话号码
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:request];
    [self.view addSubview:callWebview];
}

然后,监听电话,首先需要我们导入一个框架并引入头文件:

// 导入框架 CoreTelephony.framework
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>

监测电话:

// 监测电话
- (void)monitorCall {
    self.callCenter.callEventHandler = ^(CTCall* call) {
        if (call.callState == CTCallStateDisconnected) {
            NSLog(@"电话结束或挂断电话");
        } else if (call.callState == CTCallStateConnected){
            NSLog(@"电话接通");
        } else if(call.callState == CTCallStateIncoming) {
            NSLog(@"来电话");
        } else if (call.callState ==CTCallStateDialing) {
            NSLog(@"拨号打电话(在应用内调用打电话功能)");
        }
    };
}

#pragma mark - getter Methods

- (CTCallCenter *)callCenter {
    if (!_callCenter) {
        _callCenter = [[CTCallCenter alloc] init];
    }
    return _callCenter;
}

// 注:值得说明的是,CTCallCenter 呼叫中心必须强引用,防止对象被释放掉而无法监测电话。

 

场景:

1、点击按钮,拨号时:

2016-06-08 16:38:14.334 Demo_监听电话状态[5732:1781472] applicationWillResignActive
2016-06-08 16:38:15.520 Demo_监听电话状态[5732:1781472] applicationDidBecomeActive
2016-06-08 16:38:15.621 Demo_监听电话状态[5732:1784552] 拨号打电话(在应用内调用打电话功能)

2、手机来电,然后挂断:

2016-06-08 16:40:11.479 Demo_监听电话状态[5732:1785743] 来电话
2016-06-08 16:40:11.819 Demo_监听电话状态[5732:1781472] applicationWillResignActive
2016-06-08 16:40:13.746 Demo_监听电话状态[5732:1785743] 电话结束或挂断电话
2016-06-08 16:40:15.267 Demo_监听电话状态[5732:1781472] applicationDidBecomeActive

3.手机来电,接通,然后挂断:

2016-06-08 16:42:11.479 Demo_监听电话状态[5732:1785743] 来电话
2016-06-08 16:42:11.819 Demo_监听电话状态[5732:1781472] applicationWillResignActive
2016-06-08 16:42:11.919 Demo_监听电话状态[5732:1785743] 电话接通
2016-06-08 16:42:13.746 Demo_监听电话状态[5732:1785743] 电话结束或挂断电话
2016-06-08 16:42:15.267 Demo_监听电话状态[5732:1781472] applicationDidBecomeActive

 

尊重作者劳动成果,转载请注明: 【kingdev】

posted @ 2016-06-08 16:46  Kingdev  阅读(3456)  评论(0编辑  收藏  举报