'How to keep track of time from foreground to background mode

In my app I have to keep track of app idle time so that when app goes into background current idle time should be saved as I have to call an api from background when app timeout period is exceeded.

Currently we have just set a timer to logout app & call api if idle time is exceeded which is working fine for foreground. I need to do same even when app is in background.

 idleTimer = Timer.scheduledTimer(timeInterval: timeoutInSeconds, target: self,
  selector: #selector(SCMApplication.timeHasExceeded),userInfo: nil, repeats: false 

  @objc private func timeHasExceeded() {

        if User.shared.isLoggedIn() {
    
            // deregister the timer
    
            if let idleTimer = idleTimer {
    
                idleTimer.invalidate()
 
                self.idleTimer = nil
    

            }
    
                self.logOut()

            }

        }
    }
    
    
    private func logOut() {
        print("session timed out")
        UIApplication.logout()
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source