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!
Scheduled NSTimer when app is in background?
You shouldn't solve this problem by setting a timer, because you're not allowed to execute any code in the background. Imagine what will happen if the user restarts his iPhone in the meantime or with some other edge cases.
Use the applicationDidEnterBackground:
and applicationWillEnterForeground:
methods of your AppDelegate to get the behavior you want. It's way more robust, because it will also work when your App is completely killed because of a reboot or memory pressure.
You can save the time the timer will fire next when your App is going to the background and check if you should take action when the App comes back to the foreground. Also stop and start the timer in this methods. While your App is running you could use a timer to trigger the update at the right moment.
Related Topics
Wrong Frame Size in Viewdidload
How to Fix Failed to Fetch Default Token Error
Why Is Uiscrollview Leaving Space on Top and Does Not Scroll to the Bottom
How to Fill Uitableview with a Data from Dictionary. Swift
How to Pass Data from One Container to Another, Both Embedded in the Same Uiviewcontroller in Swift
Appdelegate and Scenedelegate When Supporting iOS 12 and 13
Working with Live Photos in Playground
Remove Space Navigationtitle But Not the Back Button
Count Unseen Messages with Firebase in Swift
Set a Maximum Number of Children in Firebase
iOS Avfoundation: Setting Orientation of Video
Swiftui: Navigationdestinationlink Deprecated
Nehotspothelper Annotations Not Appearing
Combine Onchange and Onappear Events in Swiftui View
Swift - Using Replacerange() to Change Certain Occurrences in a String