通过CTCall
的callEventHandler
回调block来获得通话状态的改变.
代码如下:
#import <CoreTelephony/CTCall.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
@interface MMCallNotificationManager()
@property (nonatomic, strong) CTCallCenter *callCenter;
@property (nonatomic) BOOL callWasStarted;
@end
@implementation MMCallNotificationManager
- (instancetype)init
{
self = [super init];
if (self) {
self.callCenter = [[CTCallCenter alloc] init];
self.callWasStarted = NO;
__weak __typeof__(self) weakSelf = self;
[self.callCenter setCallEventHandler:^(CTCall *call) {
if ([[call callState] isEqual:CTCallStateIncoming] ||
[[call callState] isEqual:CTCallStateDialing]) {
if (weakSelf.callWasStarted == NO) {
weakSelf.callWasStarted = YES;
NSLog(@"Call was started.");
}
} else if ([[call callState] isEqual:CTCallStateDisconnected]) {
if (weakSelf.callWasStarted == YES)
{
weakSelf.callWasStarted = NO;
NSLog(@"Call was ended.");
}
}
}];
}
return self;
}
@end
sim卡问题:
如果应用会让用户去拨打电话,但是当设备没有sim卡的时候, 使用iOS 的URLstelprompt:
会导致在iOS8下界面会闪两下.
可以用如下代码检查sim卡是否插上了:
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
- (IBAction)handleCallButtonPress:(id)sender
{
CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
NSString *code = [networkInfo.subscriberCellularProvider mobileCountryCode];
//this is nil if you take out sim card.
if (code == nil) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"aler.error",nil)
message:NSLocalizedString(@"alert.message.no_sim_card",nil)
delegate:nil
cancelButtonTitle:NSLocalizedString(@"alert.button_dimiss", nil)
otherButtonTitles:nil];
[alertView show];
return;
}
//make regular phone prompt (with call confirmation)
NSURL *phoneUrl = [NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@",phoneNumberString]];
if ([[UIApplication sharedApplication] canOpenURL:phoneUrl]) {
[[UIApplication sharedApplication] openURL:phoneUrl];
}
}