0

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()
    }
timbre timbre
  • 12,648
  • 10
  • 46
  • 77
jayant rawat
  • 318
  • 2
  • 12
  • "I have to call an api from background when app timeout period is exceeded." This is impossible to do in a reliable way. You will need to redesign the API to remove this requirement. There is no promise that you will be allowed to run code at some arbitrary point in the future when you're not in the foreground. (This is by design.) You can schedule background tasks that request some time in the background, but there is no guarantee they'll be run when you want. https://developer.apple.com/documentation/backgroundtasks – Rob Napier Feb 17 '22 at 16:31
  • 1
    The way to implement this API is to turn it around. The client should send some "ping" to the API periodically. When the server stops seeing your ping, it should mark the client idle. This is necessary in any case, since it's possible the phone may be turned off or disconnected from the network. There's never a promise that code will be run at some future time on any platform. How would your system handle those cases? (Just handle all cases that same way.) – Rob Napier Feb 17 '22 at 16:40
  • You can calculate time between `applicationDidEnterBackground` and `applicationWillEnterForeground` and act accordingly – ChanOnly123 Feb 17 '22 at 18:12

0 Answers0