我正在尝试根据通话状态更改按钮状态。 我使用此处的代码来检测呼叫状态:How to get a call event using CTCallCenter:setCallEventHandler: that occurred while the app was suspended?
当app在前台时,它可以正常工作。但它根本不适用于后台。在CTCallCenter.callEventHandler
的文档中:
当您的应用程序恢复活动状态时,它会收到一个 每次调用改变状态的调用事件 - 无论状态多少 更改应用程序暂停时遇到的呼叫。该 根据您的申请,将单个呼叫事件发送给您的处理程序 返回活动状态,描述呼叫的状态 时间。
但是,当应用恢复活动时,我没有收到任何通话事件。当应用程序处于前台时,我得到的是上次保存的呼叫状态。如何在后台检测呼叫状态?
这是我的代码:
AppDelegate.swift
let callСenter = CTCallCenter()
func block (call:CTCall!)
{
callState = String(call.callState)
print(call.callState)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
//check for call state
callСenter.callEventHandler = block
...
return true
}
ViewController.swift
override func viewDidLoad()
{
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(cameBackFromSleep),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil
)
...
}
func cameBackFromSleep()
{
self.viewWillAppear(true)
}
override func viewWillAppear(_ animated: Bool)
{
switch callState
{
case "CTCallStateConnected":
print("callState: ", callState)
self.textLabel.isHidden = true
startBtnAnimation()
case "CTCallStateDisconnected":
print("callState: ", callState)
self.textLabel.center.y += self.view.bounds.height
self.textLabel.isHidden = false
stopBtnAnimation()
default: break
}
}
答案 0 :(得分:3)
最后,我解决了!我使用了这个答案中的代码:Find if user is in a call or not?
我从AppDelegate
删除了所有内容,所有工作都在ViewController
中完成:
override func viewDidLoad()
{
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(cameBackFromSleep),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil
)
...
}
private func isOnPhoneCall() -> Bool
{
let callCntr = CTCallCenter()
if let calls = callCntr.currentCalls
{
for call in calls
{
if call.callState == CTCallStateConnected || call.callState == CTCallStateDialing || call.callState == CTCallStateIncoming
{
print("In call")
return true
}
}
}
print("No calls")
return false
}
func cameBackFromSleep()
{
self.viewWillAppear(true)
}
override func viewWillAppear(_ animated: Bool)
{
print("is on call", isOnPhoneCall())
switch isOnPhoneCall()
{
case true:
print("startBtnAnimation")
startBtnAnimation()
recordBtnIsPressed = true
case false:
print("stopBtnAnimation")
stopBtnAnimation()
recordBtnIsPressed = false
default: break
}
}
现在它运作正常。不确定为什么CTCallCenter
在AppDelegate
中工作得如此奇怪。