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
- Save off a time stamp as soon as your app transitions to the background.
- Terminate your timers
When your app re-enters the foreground:
From applicationWillEnterForeground
edit or 'didUdateLocations'
- Read the save time stamp
- Use
timeIntervalSinceDate
to get the lapsed time in seconds - 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
What Is the Meaning of This Declaration
Uicollectionview with a Sticky Header
Bringing a Subview to Be in Front of All Other Views
Xcode Won't Let to Build for Device After Denying Codesign to Access Keychain
How to Set Fake Gps Location on iOS Real Device
iOS Documents Directory Size Limit
Delay/Wait in a Test Case of Xcode UI Testing
Frosted Glass (iOS 7 Blur) Effect
How to Get the Size of a Scaled Uiimage in Uiimageview
How to Add Headerview in Uicollectionview Like Uitableview's Tableheaderview
iOS - Uiimagewritetosavedphotosalbum
How to Loop Over Struct Properties in Swift
How to Programmatically Check Support of 'Face Id' and 'Touch Id'