I need to run a timer when the user is in app and also when the app is in background.
The context is: if he is on a specific view controller, after 5 min will be redirected to main view controller. The timer should redirect him if the app stays in background and enters the app. Any idea how can I achieve this?
Another way for doing this in Swift 3:
First take current time in seconds and save it into user defaults
When an app become active you may compare last active time(which is saved into user defaults) with the current time. (Note: both of elements have to be in one format)
And that's all. You can do whatever you want if condition is true.
You can't do this with a normal
NSTimer
as there is no support for backgrounding. It is however achievable very easily using another method.In your AppDelegate you have two methods.
applicationWillResignActive
andapplicationDidBecomeActive
. In the resign method you simply need to persist the currentNSDate
into theNSUserDefaults
and in the active method, retrieve it and compare it against the currentNSDate
to get the amount of time the app was inactive for.Code examples: