How to Run Timer Though the App Entered Background or Is Terminated

How to run timer though the app entered background or is terminated

If your application is terminated, you will not be able to continue processing. To operate in the background, there are such things as background tasks, but it sounds like your use case does not warrant them. Because your incrementing is linear and computable, you could assign your start date to NSUserDefaults, then load it back when your application resumes and update your count.

[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"start_time"];
NSNumber *start = [[NSUserDefaults standardUserDefaults] objectForKey:@"start_time"];
countNum = ceil([[NSDate date] timeIntervalSince1970] * 100) - ceil([start doubleValue] * 100);

How to set a timer to run when an app is both in foreground and in background?

You can't run a timer in the background forever, it's not one of the background modes allowed by the OS so it will get terminated at some point. Wrapping it in a background task will only buy you a few extra minutes (about 10) at the most.

To properly track time when your app enters the background you need to:

From applicationDidEnterBackground

  1. Save off a time stamp as soon as your app transitions to the background.
  2. Terminate your timers

When your app re-enters the foreground:

From applicationWillEnterForeground edit or 'didUdateLocations'

  1. Read the save time stamp
  2. Use timeIntervalSinceDate to get the lapsed time in seconds
  3. Restart your timer using the time span to set the remaining time

Run timer in background

It's possible through a token that identifies a request to run in the background.

Like this: var bgTask = UIBackgroundTaskIdentifier()

Here is how to use it:

var bgTask = UIBackgroundTaskIdentifier()
bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(bgTask)
})
let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(notificationReceived), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)

I hope it would be useful!

Continue countdown timer when app is running in background/suspended

What I suggest is cancel the timer and store a NSDate when the app goes to the background.
You can use this notification to detect the app going to the background:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "pauseApp", name: UIApplicationDidEnterBackgroundNotification, object: nil)

Then cancel the timer and store the date:

func pauseApp(){
self.stop() //invalidate timer
self.currentBackgroundDate = NSDate()
}

Use this notification to detect the user coming back:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "startApp", name: UIApplicationDidBecomeActiveNotification, object: nil)

Then calculate the difference from the stored date to the current date, update your counter and start the timer again:

func startApp(){
let difference = self.currentBackgroundDate.timeIntervalSinceDate(NSDate())
self.handler(difference) //update difference
self.start() //start timer
}


Related Topics



Leave a reply



Submit