'My countdown circular timer is not working as expected in Swiftui
I have a problem and I dont know what's the issue, maybe you can help me out with this. I made a Circular Timer (a circle which count how much time is remaining), but I have 2 big issues .
After I close the view and come back, the timer is starting again from the start and it goes faster. And that's on repeat, after the view is again closed, it starts from the start and it goes faster.
Second issue is that I don't think is counting Right. For example "deliveryDate" is set to be at 4:00 PM, but is 3:58 PM and the Circular Timer is already completed.
NOTE : Is a delivery app, user can select the "deliveryDate".
My timer count with the help of 2 variables: "syncViewModel._order.date" - This is the Date when the order is placed and "syncViewModel._order.deliveryDate". - This is the date that the user want the order to be delieverd
I'll share my code below
This is the Circular Timer :
let timer = Timer
.publish(every: 10, on: .main, in: .common)
.autoconnect()
@available(iOS 15, *)
struct CircularTimerr: View {
@EnvironmentObject var syncViewModel : SyncViewModel
@State var startPointValue : CGFloat
var endPointValue : CGFloat
var body: some View {
VStack{
ZStack{
Circle()
.fill(Color.clear)
.frame(width: 250, height: 250)
.overlay(
Circle().stroke(Color.gray.opacity(22/100), lineWidth: 5)
)
Circle()
.fill(Color.clear)
.frame(width: 250, height: 250)
.overlay(
Circle().trim(from:0, to: progress())
.stroke(
style: StrokeStyle(
lineWidth: 5,
lineCap: .round,
lineJoin:.round
)
)
.foregroundColor(
(completed() ? Color.orange : Color.orange)
).animation(
.easeInOut(duration: 0.2)
)
) }
.onAppear{
print(startPointValue)
print(endPointValue)
}
}.onReceive(timer) { time in
if (self.startPointValue < self.endPointValue) {
self.startPointValue += 1
}
}
}
func completed() -> Bool {
return progress() == 1
}
func progress() -> CGFloat {
return ( startPointValue / endPointValue)
}
}
This is the view
struct OrderConfirmedVieww: View {
@EnvironmentObject var syncViewModel : SyncViewModel
var body: some View {
VStack {
CircularTimer(startPointValue: CGFloat(dateFormatTime(date: syncViewModel._order.date ?? "").timeIntervalSinceNow), endPointValue: CGFloat(dateFormatTime(date: syncViewModel._order.deliveryDate ?? "").timeIntervalSinceNow))
}
}
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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
