Countdown timer SwiftUI - ios

How to make a countdown timer daily at a specific time. When I open the application again, the timer is reset and the countdown starts again, I'm trying to figure out how to make the timer start again after its time has elapsed..
For example, so that this timer starts over every day at 6 pm
struct TimerView: View {
//MARK: - PROPERTIES
#State var timeRemaining = 24*60*60
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
//MARK: - BODY
var body: some View {
Text("\(timeString(time: timeRemaining))")
.font(.system(size: 60))
.frame(height: 80.0)
.frame(minWidth: 0, maxWidth: .infinity)
.foregroundColor(.white)
.background(Color.black)
.onReceive(timer){ _ in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
}else{
self.timer.upstream.connect().cancel()
}
}
}
//Convert the time into 24hr (24:00:00) format
func timeString(time: Int) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}
}

the timer is reset and the countdown starts again
You could try to play with UserDefaults to store variables in the device's memory.
Here is the Documentation : https://developer.apple.com/documentation/foundation/userdefaults

Take a look at TimelineView and AppStorage e.g.
#AppStorage("StartDate") var startDate: Date
...
TimelineView(.periodic(from: startDate, by: 1)) { context in
AnalogTimerView(date: context.date)
}

Related

How do I animate a number in swift?

I want to animate a number. The animation I want to achieve is going from 0 increasing all the way up to the current number (at high speed). In this project, the number is the number of steps a user has taken. Is there a way this can be achieved?
LazyVStack{
ForEach(steps, id: \.id) { step in
//Here is the number I want to be animated
Text("\(step.count)")
.font(.custom(customFont, size: 50))
Text("Steps")
.font(.custom(customFont, size: 25))
.multilineTextAlignment(.center)
}
}
I believe I have a function along the right lines, I just need to apply it! Here is the function:
func addNumberWithRollingAnimation() {
withAnimation {
// Decide on the number of animation tasks
let animationDuration = 1000 // milliseconds
let tasks = min(abs(self.enteredNumber), 100)
let taskDuration = (animationDuration / tasks)
// add the remainder of our entered num from the steps
total += self.enteredNumber % tasks
// For each task
(0..<tasks).forEach { task in
// create the period of time when we want to update the number
// I chose to run the animation over a second
let updateTimeInterval = DispatchTimeInterval.milliseconds(task * taskDuration)
let deadline = DispatchTime.now() + updateTimeInterval
// tell dispatch queue to run task after the deadline
DispatchQueue.main.asyncAfter(deadline: deadline) {
// Add piece of the entire entered number to our total
self.total += Int(self.enteredNumber / tasks)
}
}
}
}
Here is a utility function called Timer.animateNumber() which takes a Binding<Int> to animate, a Binding<Bool> busy which indicates if the value is currently animating, and Int start value, an Int end value, and a Double duration in seconds.
To use it, you need to define an #State private var number: Int to animate, and #State private var busy: Bool to keep track of the animation's state. This can also be used to terminate the animation early by just setting busy to false. Pass in your start value, end value, and duration in seconds.
This demo shows two animated numbers. The first counts up from 1 to 10000 in 1 second. The second counts down from 20 to 0 in 20 seconds. The Stop All button can be used to stop both animations.
extension Timer {
static func animateNumber(number: Binding<Int>, busy: Binding<Bool>, start: Int, end: Int, duration: Double = 1.0) {
busy.wrappedValue = true
let startTime = Date()
Timer.scheduledTimer(withTimeInterval: 1/120, repeats: true) { timer in
let now = Date()
let interval = now.timeIntervalSince(startTime)
if !busy.wrappedValue {
timer.invalidate()
}
if interval >= duration {
number.wrappedValue = end
timer.invalidate()
busy.wrappedValue = false
} else {
number.wrappedValue = start + Int(Double(end - start)*(interval/duration))
}
}
}
}
struct ContentView: View {
#State private var number: Int = 0
#State private var number2: Int = 0
#State private var busy: Bool = false
#State private var busy2: Bool = false
var body: some View {
VStack(spacing: 20) {
Text(String(number))
Button("Go") {
if !busy {
Timer.animateNumber(number: $number, busy: $busy, start: 1, end: 10000, duration: 1)
}
}
Text(String(number2))
Button("Go") {
if !busy2 {
Timer.animateNumber(number: $number2, busy: $busy2, start: 20, end: 0, duration: 20)
}
}
Button("Stop All") {
busy = false
busy2 = false
}
}
}
}

#Publish counters not in sync inside timer SwiftUI

I'm working on an app where I'm using a timer to count down time left in a workout and also count up for total time. My counters are out of sync, looks like it's less than a second off. I'm wondering if it has something to do with #Publish, maybe one fires before the other. Any idea what's happening and how to fix it?
class TimeManager: ObservableObject {
#Published var totalTime: Double = 0.0
#Published var timeRemaining: Double = 180.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) {
self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] timer in
guard let self = self else { return }
self.timeRemaining -= 0.1
self.totalTime += 0.1
}
}
}
then my view
#ObservedObject var timeManager = TimeManager()
...
var body: some View {
VStack {
let time = timeManager.timeRemaining
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
ZStack {
Progress()
Text(String(format:"%02i:%02i", minutes, seconds))
.font(.system(size: 60))
}
let total = timeManager.totalTime
let totalMins = Int(total) / 60 % 60
let totalSecs = Int(total) % 60
Text(String(format:"%02i:%02i", totalMins, totalSecs))
.font(.system(size: 40))
}
}
Your time values are in sync. The reason for the behaviour you are seeing is the Double / Int conversions and the rounding applied while display the Texts. Try this line:
Text("\(timeManager.timeRemaining + timeManager.totalTime)")
and you will see this allways adding up to 180.
You could try Int values in your Viewmodel decrementing/incrementing by 1 and a DateComponentsFormatter to format the values in your View.
let componentsFormatter = DateComponentsFormatter()
Text("\(componentsFormatter.string(from: Double(timeManager.timeRemaining)) ?? "NAN")")
.font(.system(size: 60))
You would of course need to tweek the formatter to display the time the way you want it to be. But I agree with Paulw11. This seems like a bad design. It would be better to have a single source of truth as a Date and go from there.
Maybe calculate your 2nd value based on the first when you decrement the time. For example like this:
remaining = (180 - total) >= 0 ? (180 - total) : 0

Observe if my value reached zero in Swift? [duplicate]

It is possible to pass a date to Text() in SwiftUI, then format it as a timer using the style argument. However, a countdown like this never stops, it just keeps incrementing after zero. How to make it stop at 0?
func nextRollTime(in seconds: Int) -> Date {
let date = Calendar.current.date(byAdding: .second, value: seconds, to: Date())
return date ?? Date()
}
Above is the function I use to start a countdown, then I pass it as follows:
Text(nextRollTime(in: 20), style: .timer)
Here is a demo of possible approach - as .timer run from now for ever (by design), the idea is to replace it with regular text once specified period is over.
Tested with Xcode 12b3 / iOS 14.
struct DemoView: View {
#State private var run = false
var body: some View {
VStack {
if run {
Text(nextRollTime(in: 10), style: .timer)
} else {
Text("0:00")
}
}
.font(Font.system(.title, design: .monospaced))
.onAppear {
self.run = true
}
}
func nextRollTime(in seconds: Int) -> Date {
let date = Calendar.current.date(byAdding: .second, value: seconds, to: Date())
DispatchQueue.main.asyncAfter(deadline: .now() + Double(seconds)) {
self.run = false
}
return date ?? Date()
}
}

Basing a StopWatch off of Date() - SwiftUI

I am wanting to have a stopwatch in my app that runs completely off the device's time. I have my code below which takes the time in which the start button is pressed, and then every second updates the secondsElapsed to be the difference between the startTime and current. I am getting stuck on implementing a pause function. If I just invalidate the update timer, then the timer will restart having pretty much carried on from where it left off. Any ideas on how this could be done?
class StopWatchManager: ObservableObject{
#Published var secondsElapsed = 0
var startTime: Date = Date()
var timer = Timer()
func startWatch(){
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ timer in
let current = Date()
let diffComponents = Calendar.current.dateComponents([.second], from: self.startTime, to: current)
let seconds = (diffComponents.second ?? 0)
self.secondsElapsed = seconds
}
}
func pauseWatch(){
timer.invalidate()
}
}
I display the stopwatch using this code below:
struct ContentView: View {
#ObservedObject var stopWatchManager = StopWatchManager()
var body: some View{
HStack{
Button("Start"){
stopWatchManager.startWatch()
}
Text("\(stopWatchManager.secondsElapsed)")
Button("Pause"){
stopWatchManager.pauseWatch()
}
}
}
}
Yes. Here is how to do it:
When pause is pressed, note the current time and compute the elapsed time for the timer. Invalidate the update timer.
When the timer is resumed, take the current time and subtract the elapsed time. Make that the startTime and restart the update timer.
Here's the updated code:
class StopWatchManager: ObservableObject{
#Published var secondsElapsed = 0
var startTime: Date = Date()
var elapsedTime = 0.0
var paused = false
var running = false
var timer = Timer()
func startWatch(){
guard !running else { return }
if paused {
startTime = Date().addingTimeInterval(-elapsedTime)
} else {
startTime = Date()
}
paused = false
running = true
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){ timer in
let current = Date()
let diffComponents = Calendar.current.dateComponents([.second], from: self.startTime, to: current)
let seconds = (diffComponents.second ?? 0)
self.secondsElapsed = seconds
}
}
func pauseWatch(){
guard !paused else { return }
timer.invalidate()
elapsedTime = Date().timeIntervalSince(startTime)
paused = true
running = false
}
}
Things to note:
I changed the timer interval to 0.1 from 1 to avoid missing updates.
I added paused and running state variables to keep the buttons from being pressed more than once in a row.

Swift Timer() trouble

I've done a simple timer in Swift. All is well apart from when the seconds reach 59 seconds. Instead of going back to zero they just carry on going. Would someone would be able to point out where I'm going wrong and why this is happening?
#IBAction func startButtonDidTouch(_ sender: Any) {
if !timerIsRunning{
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true)
timerIsRunning = true
}
}
#objc func updateTimer() {
totalSeconds += 0.01
let totalSecondsTimes100: Int = Int(totalSeconds*100)
let minutes = Int(totalSeconds/60)
let timerChoice = Double(minutes)
let minStr = (minutes == 0) ? "00" : "0\(minutes)"
let secStr = (totalSeconds < 9) ? "0\(Float(totalSecondsTimes100)/100)" : "\(Float(totalSecondsTimes100)/100)"
switch Int(timerChoice) {
case Int(timerCountdownLabel.text!)!:
timerLabel.text = "\(minStr):\(secStr)"
audioPlayer.play()
timer.invalidate()
timerIsRunning = false
default:
timerLabel.text = "\(minStr):\(secStr)"
}
}
You should calculate the seconds as:
let seconds = totalSeconds % 60
and then use seconds in your calculation of secStr instead of using totalSeconds.
There are better ways to write your code:
#objc func updateTimer() {
totalSeconds += 0.01
let minutes = Int(totalSeconds) / 60
let seconds = totalSeconds.remainder(dividingBy: 60)
let timeStr = String(format: "%02d:%06.3f", minutes, seconds)
timerLabel.text = timeStr
if Int(timerCountdonwLabel.text!)! == minutes {
audioPlayer.play()
timer.invalidate()
timerIsRunning = false
}
}
And you really shouldn't keep track of time simply by adding 0.01 to totalSeconds. A Timer is not accurate. Your clock will drift over time. It's best to save a timestamp (Date()) when you start the timer and get the current timestamp (Date()) inside updateTimer and get the difference between the two.
Here is a timer function that outputs format minutes:seconds:milliseconds, compare with your code and you'll find what's wrong with your code.
private weak var timer: Timer?
private var startTime: Double = 0
private var elapsed: Double = 0
private var time: Double = 0
private func startTimer(){
startTime = Date().timeIntervalSinceReferenceDate - elapsed
timer = Timer.scheduledTimer(timeInterval: (0.01), target: self, selector: #selector(updateTimeLabel), userInfo: nil, repeats: true)
}
private func stopTimer(){
elapsed = Date().timeIntervalSinceReferenceDate - startTime
timer?.invalidate()
}
#objc func updateTimeLabel(){
time = Date().timeIntervalSinceReferenceDate - startTime
let minutes = UInt8(time / 60.0)
let timeNoMin = time - (TimeInterval(minutes) * 60)
let seconds = UInt8(timeNoMin)
let timeNoSec = timeNoMin - (TimeInterval(seconds))
let milliseconds = UInt16(timeNoSec * 100)
let strMinutes = String(minutes)
var strSeconds = ""
if strMinutes == "0" {
strSeconds = String(seconds)
}
else {
strSeconds = String(format: "%02d", seconds)
}
let strMilliseconds = String(format: "%02d"), milliseconds)
if strMinutes != "0" {
timerLabel.text = "\(strMinutes):\(strSeconds).\(strMilliseconds)"
}
else {
timerLabel.text = "\(strSeconds).\(strMilliseconds)"
}
}
To get minutes and seconds from a floating point total number of seconds elapsed, elapsed you can:
To get minutes, divide by 60.0 and truncate to the nearest integer:
let minutes = Int(elapsed / 60)
To get seconds, get the remainder, either via:
let seconds = elapsed - Double(minutes) * 60
Or
let seconds = elapsed.truncatingRemainder(dividingBy: 60)
A couple of other observations:
There's no point in running a timer every 0.01 seconds when the screen refresh rate is usually capped at 60 frames per second. If you want to update it with the greatest frequency, use a CADisplayLink which is timed not only for maximum screen refresh rate, but also fires optimally to allow the update to happen before the next frame is to be rendered.
You should not use timer to increment the elapsed time by 0.01 (or any fixed interval) because you have no assurances that it will actually fire with that frequency. If something, for example, momentarily blocks the main thread by 200 milliseconds, you don't want this to affect your calculation of the amount of time that has elapsed.
Instead, save the start time when the timer starts, and every time the timer fires recalculate the elapsed time and format the results accordingly.
To complicate this further, you should not even be comparing Date() instances (or CFAbsoluteTimeGetCurrent() values) because, as the documentation warns us:
Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.
Instead, you should use a mach_absolute_time based calculation (such as returned by CACurrentMediaTime()), for which repeated calls are assured to return accurately elapsed time calculations.
The only time you should use Date() or CFAbsoluteTimeGetCurrent() if your app is saving the start time in persistent storage, to be retrieved later when the app is restarted (possibly after a device reboot) to render the effect of the elapsed time between starts of an app. But this is a pretty narrow edge case.
Anyway, this yields:
var start: CFTimeInterval?
weak var displayLink: CADisplayLink?
func startTimer() {
self.displayLink?.invalidate() // just in case timer had already been started
start = CACurrentMediaTime()
let displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
displayLink.preferredFramesPerSecond = 100 // in case you're using a device that can render more than 60 fps
displayLink.add(to: .main, forMode: .commonModes)
self.displayLink = displayLink
}
#objc func handleDisplayLink(_ displayLink: CADisplayLink) {
let elapsed = CACurrentMediaTime() - start!
let minutes = Int(elapsed / 60)
let seconds = elapsed - Double(minutes) * 60
let string = String(format: "%02d:%05.2f", minutes, seconds)
label.text = string
}
func stopTimer() {
displayLink?.invalidate()
}

Resources