title: Swift Background task on applicationWillTerminate
body: <p>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.</p>
  
  <p>I have tried following thing but seems not working for me. </p>
  
  <pre><code>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
  
                         // })
                      })
                  })
              })
          }
  
      }
  
  }
  </code></pre>
  
  <p>I have already enabled following </p>
  
  <p><a href="https://i.stack.imgur.com/sXuNQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sXuNQ.png" alt="Image"></a></p>
  
  <p>Any help or suggestion would be appreciated </p>
  
  <p>thanks in advance  </p>