iOS中如何监测来电

问题

最近在做一个有录音功能的App,要求当用户接到来电时,要停止录音。该如何实现这个功能呢?

解决方案

我首先想到了AppDelegate里的applicationWillResignActive:方法,在该方法的注释中就写到到收到来电或短信时,系统会自动调用该方法,如下:

// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

但是有个问题,当程序进入后台时,也会调用这个方法,而我的App要求,即使进入后台,也可以继续录音,而在applicationWillResignActive:方法里无法判断是什么原因引起的该方法的调用(可能有方法,但我没搜到,哪位朋友知道的话分享一下),因此这个解决方案行不通。

继续查找资料,最终找到CoreTelephony框架,这个框架包含了电话相关的API,可以实现监测来电,查看运营商信息等功能。下面就是具体的实现监测来电的代码

#import "ViewController.h"

//引入框架
@import CoreTelephony;

@interface ViewController ()
@property (nonatomic, strong) CTCallCenter * center;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.center = [[CTCallCenter alloc] init];
    self.center.callEventHandler = ^(CTCall * call)
    {
        //TODO:检测到来电后的处理
    };

}
@end

这里注意一定要把center写成一个单独的属性,并且是强引用(strong),否则如果在viewDidLoad方法里创建center,viewDidLoad方法调用完后center就销毁了,就无法检测到来电了,千万不要犯这种低级错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值