struct ContentView : View {
@State private var nowDate: Date = Date()
@State private var referenceDate: Date = Date()
var timer: Timer {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {_ in
self.nowDate = Date()
}
}
var body: some View {
Text(countDownString(from: referenceDate))
.font(.largeTitle)
.onAppear(perform: {
getReferenceDate()
_ = self.timer
})
}
func countDownString(from date: Date) -> String {
let calendar = Calendar(identifier: .gregorian)
let components = calendar
.dateComponents([.day, .hour, .minute, .second],
from: nowDate, to: referenceDate
)
return String(format: "%02dd:%02dh:%02dm:%02ds",
components.day ?? 00,
components.hour ?? 00,
components.minute ?? 00,
components.second ?? 00)
}
func getReferenceDate() {
let calendar = Calendar.current
let date = calendar.date(byAdding: .minute, value: 2, to: Date())
referenceDate = date!
}
}
Essentially what I have done is generate a reference date to countdown to by calling the getReferenceDate() function in .onAppear. That date is 2 minutes from the current Date.
There should be no need for me to send you the project. The ContentView code I pasted in my reply should work for you. Either overwrite your code with this… or create a new test project and paste this into that project in place of the ContentView in that new project.
Just for exercise I adjusted the referenceDate calculation to add 24 days to the current date which would be July 27.
struct ContentView : View {
@State private var nowDate: Date = Date()
@State private var referenceDate: Date = Date()
var timer: Timer {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {_ in
self.nowDate = Date()
}
}
var body: some View {
Text(countDownString(from: referenceDate))
.font(.largeTitle)
.onAppear(perform: {
getReferenceDate()
_ = self.timer
})
}
func countDownString(from date: Date) -> String {
let calendar = Calendar(identifier: .gregorian)
let components = calendar
.dateComponents([.day, .hour, .minute, .second],
from: nowDate, to: referenceDate)
return String(format: "%02dd:%02dh:%02dm:%02ds",
components.day ?? 00,
components.hour ?? 00,
components.minute ?? 00,
components.second ?? 00)
}
func getReferenceDate() {
let calendar = Calendar.current
let date = calendar.date(byAdding: .day, value: 24, to: Date())
referenceDate = date!
}
}