持续时间后呼叫超时功能 Callkit

You*_*uer 3 ios ios10 callkit

我尝试Timer在接到电话后 12 秒添加超时,CallKit但是Appdelegate当应用程序处于后台时它不会被触发。我的代码:

self.callBackgroundHandlerIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { 
            UIApplication.shared.endBackgroundTask(self.callBackgroundHandlerIdentifier!)
            self.callBackgroundHandlerIdentifier = UIBackgroundTaskInvalid
        })
        DispatchQueue.global(qos: .userInitiated).async {
            AppDelegate.callAnswerTimer = Timer.scheduledTimer(timeInterval: 12, target: self, selector: #selector(AppDelegate.hangUpOnCallTimeOut), userInfo: nil, repeats: false)

            self.callBackgroundHandlerIdentifier = UIBackgroundTaskInvalid
        }

func hangUpOnCallTimeOut(){
        AppDelegate.timeOutTimer?.invalidate()
        AppDelegate.timeOutTimer = nil
        if #available(iOS 10.0, *) {
            ProviderDelegate.sharedInstance.endCall(uuids: ApplicationDelegate.activeCalls!) { (uuid) in }
        }
        if self.callBackgroundHandlerIdentifier != UIBackgroundTaskInvalid {
            UIApplication.shared.endBackgroundTask(self.callBackgroundHandlerIdentifier!)
        }
    }
Run Code Online (Sandbox Code Playgroud)

任何想法我做错了什么?

Dai*_*jan 6

a) 不要在后台的块中添加计时器。在主队列上运行计时器!

b) 不要过早重置 self.callBackgroundHandlerIdentifier。

:) 试试下面的代码


func ... {
    self.callBackgroundHandlerIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { 
        print("expired!")
        UIApplication.shared.endBackgroundTask(self.callBackgroundHandlerIdentifier!)
        self.callBackgroundHandlerIdentifier = UIBackgroundTaskInvalid
    })

    AppDelegate.callAnswerTimer = Timer.scheduledTimer(timeInterval: 12, target: self, selector: #selector(AppDelegate.hangUpOnCallTimeOut), userInfo: nil, repeats: false)
    }
}

func hangUpOnCallTimeOut(){
    AppDelegate.timeOutTimer?.invalidate()
    AppDelegate.timeOutTimer = nil
    if #available(iOS 10.0, *) {
        ProviderDelegate.sharedInstance.endCall(uuids: ApplicationDelegate.activeCalls!) { (uuid) in }
    }
    if self.callBackgroundHandlerIdentifier != UIBackgroundTaskInvalid {
        UIApplication.shared.endBackgroundTask(self.callBackgroundHandlerIdentifier!)
        self.callBackgroundHandlerIdentifier = UIBackgroundTaskInvalid
    }
}
Run Code Online (Sandbox Code Playgroud)