简体   繁体   中英

Swift Background task on applicationWillTerminate

I am using call kit and voip calling. I have case when user is in call and user terminate app from background then I wanted to perform some small operations like leave the calling channel, save the call etc.

I have tried following thing but seems not working for me.

var backgroundTask: UIBackgroundTaskIdentifier = .invalid

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.

    self.saveContext()

    if self.status == .inCall {

        self.backgroundTask =   UIApplication.shared.beginBackgroundTask(expirationHandler: {[unowned self] in

            NSLog("BACKGROUND TIME REMAINING %f", UIApplication.shared.backgroundTimeRemaining)

            UIApplication.shared.endBackgroundTask(self.backgroundTask)

            self.backgroundTask = .invalid



        })

        if let topVC = UIApplication.shared.topMostViewController as? CallingController {
            DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {// this line for just testing 

                topVC.sendText(string: Constants.ChannelMessages.endCall)
                DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {// after two seconds leave the channel and save record 
                    topVC.leaveChannelSaveRecord(completion: {
                        AppDelegate.shared.callManager.endCall(call: topVC.call)
                        // Let's wait for 2 seconds and end background task
                      //  DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
                            UIApplication.shared.endBackgroundTask(self.backgroundTask)
                            self.backgroundTask = .invalid

                       // })
                    })
                })
            })
        }

    }

}

I have already enabled following

图片

Any help or suggestion would be appreciated

thanks in advance

References : https://www.raywenderlich.com/5817-background-modes-tutorial-getting-started

Enable background fetch in capality.

Did enter background enable keeplive

This is a solution for background mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM