最近在作一個有錄音功能的App,要求當用戶接到來電時,要中止錄音。該如何實現這個功能呢?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.ui
可是有個問題,當程序進入後臺時,也會調用這個方法,而個人App要求,即便進入後臺,也能夠繼續錄音,而在applicationWillResignActive:
方法裏沒法判斷是什麼緣由引發的該方法的調用(可能有方法,但我沒搜到,哪位朋友知道的話分享一下),所以這個解決方案行不通。this
繼續查找資料,最終找到CoreTelephony框架,這個框架包含了電話相關的API,能夠實現監測來電,查看運營商信息等功能。下面就是具體的實現監測來電的代碼atom
#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
viewDidLoad
方法裏建立center,viewDidLoad
方法調用完後center就銷燬了,就沒法檢測到來電了,千萬不要犯這種低級錯誤。