在ApplicationWillTerminate上的Swift Background任务

时间:2019-05-25 07:10:37

标签: ios swift backgroundtaskidentifier

我正在使用呼叫工具包和voip呼叫。当用户处于通话状态并且用户从后台终止应用程序时,我想执行一些小操作,例如离开通话通道,保存通话等。

我尝试了以下操作,但似乎不适合我。

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

                       // })
                    })
                })
            })
        }

    }

}

我已经启用了

Image

任何帮助或建议将不胜感激

提前感谢

1 个答案:

答案 0 :(得分:0)

参考文献:https://www.raywenderlich.com/5817-background-modes-tutorial-getting-started

启用后台获取功能。

输入后台启用keeplive

这是后台模式的解决方案。