Creating a timer in Swift is fairly straightforward, but it's important to note that iOS restricts background execution to maintain battery life and system performance. However, you can make use of background tasks to ensure your operations have some additional time to complete when your app goes into the background.
First, let's create a simple Timer instance that you can control with a button and that will automatically stop when the object containing it is deallocated (deinit). To give the timer operation additional time to complete when the app goes into the background, you'll need to use UIApplication.shared.beginBackgroundTask and endBackgroundTask.
Here's an example of a Swift class that sets up a timer with these requirements:
import UIKit
class BackgroundTimer {
private var timer: Timer?
private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
init() {
startTimer()
}
deinit {
stopTimer()
}
func startTimer() {
if backgroundTaskIdentifier != .invalid {
UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
backgroundTaskIdentifier = .invalid
}
// Start a new background task if the app goes to the background
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask { [weak self] in
self?.endBackgroundTask()
}
// Invalidate the old timer before creating a new one
timer?.invalidate()
// Setup the new timer
timer = Timer.scheduledTimer(timeInterval: 120, target: self,
selector: #selector(timerDidFire), userInfo: nil, repeats: false)
}
@objc private func timerDidFire() {
print("Timer fired!")
stopTimer()
}
private func stopTimer() {
timer?.invalidate()
timer = nil
endBackgroundTask()
}
private func endBackgroundTask() {
if backgroundTaskIdentifier != .invalid {
UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
backgroundTaskIdentifier = .invalid
}
}
func restartTimer() {
startTimer()
}
}
To use this class in your view controller, you might add a button and tie its action to restarting the timer:
class ViewController: UIViewController {
private var backgroundTimer: BackgroundTimer?
override func viewDidLoad() {
super.viewDidLoad()
backgroundTimer = BackgroundTimer()
}
@IBAction func restartButtonTapped(_ sender: UIButton) {
backgroundTimer?.restartTimer()
}
deinit {
backgroundTimer?.stopTimer()
}
}
Remember to add an action to your button in the storyboard or programmatically bind it to restartButtonTapped to restart the timer.
You should be aware that even with the beginBackgroundTask call, iOS does not guarantee that your app will continue to run in the background until your timer fires. Background execution time is finite and limited by the system, and if your timer is meant to run for 2 minutes, there's a chance it may not get that much time. Normally, background tasks are granted up to 30 seconds to complete. Therefore, if you absolutely need a task to complete after a certain time in the background, you must consider other strategies, such as local notifications or server-side triggers.