Search code examples
iosios10callkit

call timeout function after duration Callkit


I tried to add a timeout Timer 12 secs after receiving a call with CallKit but it doesn't get fired in Appdelegate when the app is in background. My code:

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!)
        }
    }

Any ideas what I'm doing wrong?


Solution

  • a) dont add a timer in a block on the background. run the timer on the main queue!

    b) dont reset self.callBackgroundHandlerIdentifier too early.

    :) try below code


    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
        }
    }