TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How to make a circular timer with Dates in SwiftUI?

Forums > SwiftUI

I need some help. I figured out how to make a Circular Timer, but instead of that, I want to make it with Dates, and my example is using Int values. For example, I'm trying to countdown from a Future Date ( Example : February 4 11:00 PM ) to Date ( February 4 9:00 PM ).

This is the code that I wrote :

import SwiftUI

let timer = Timer
    .publish(every: 1, on: .main, in: .common)
    .autoconnect()

struct CircularTimer: View {
    @State var counter: Int = 0
    var countTo: Int = 120
    var nowDate = Date()
    var futureDate = Date.distantFuture
    var body: some View {
        VStack{
            ZStack{
                Circle()
                    .fill(Color.clear)
                    .frame(width: 250, height: 250)
                    .overlay(
                        Circle().stroke(Color.green, lineWidth: 25)
                )

                Circle()
                    .fill(Color.clear)
                    .frame(width: 250, height: 250)
                    .overlay(
                        Circle().trim(from:0, to: progress())
                            .stroke(
                                style: StrokeStyle(
                                    lineWidth: 25,
                                    lineCap: .round,
                                    lineJoin:.round
                                )
                            )
                            .foregroundColor(
                                (completed() ? Color.orange : Color.red)
                            ).animation(
                                .easeInOut(duration: 0.2)
                            )
                    )
            }
        }.onReceive(timer) { time in
            if (self.counter < self.countTo) {
                self.counter += 1
            }

        }
    }
    func completed() -> Bool {
        return progress() == 1
    }

    func progress() -> CGFloat {
        return (CGFloat(counter) / CGFloat(countTo))
    }
}

If anyone can help me I will be grateful . Thanks !

1      

One of programming's core principles is reusability. In this case you have a nice looking timer that counts from a given value down to zero. This code works! And it looks nice! Why do you want to recode this, and possibly introduce complexity and errors? Think about reusing this code without modifying it.

Instead, consider adding an abstraction layer between your model and your view. I think this is called the "ViewModel". Have you watched videos on MVVM development pattern?

See > Model-View-ViewModel

An over simplified take on this: Keep the starting and ending dates inside your application's model. This is where you design and execute your business rules. This is where you make sure the starting and ending dates are meaningful, etc.

Your CircularTimer view just exists as a Lego block. It takes a starting point and counts down to zero, then just draws circles to the screen.

Use your ViewModel to turn a starting and ending date into a the starting point. Then send the starting point to your reusable CircularTimer.

1      

Thanks for the answer, @Obelix. I made this example following an Yt tutorial, but this is not really what I Want. I am making a delivery application where client can select the delivery time. For Example if now is 10 AM and the selected Delivery Time is 12 AM, I want to make something, like a countdown, how much time is left..

This is what I am showing inside of the circular Timer :

  Text(countDownString(from: dateFormatTime(date: syncViewModel._order.deliveryDate ?? "")))
                .font(.largeTitle)
                .foregroundColor(.colorGrayDark)

      func countDownString(from date: Date) -> String {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar
            .dateComponents([.minute],
                            from: nowDate,
                            to: dateFormatTime(date: syncViewModel._order.deliveryDate ?? ""))
        return String(format: "%02d'",
                      components.minute ?? 00)

    }
    func dateFormatTime(date : String) -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = .current
        return dateFormatter.date(from: date) ?? Date.now
    }

1      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.