SwiftUI - How to create countdown date timer with calendar function | Apple iOS Xcode YouTube Seminar #2

 

Swift5.1.2 Xcode11.2.1 SwiftUI


- how to create iOS countdown timer
- control date and calendar library in SwiftUI
- use timer function to calculate current time difference


Countdown date and time for your birthday, Christmas or holiday with your original app


* Here is the highlight of YouTube tutorial.

Christmas, retirement or birthday are one of your precious time you should count. You may miss them with third party's app created by somebody else you don't know.

So, how about creating it by yourself. Don't worry. It's very easy for novice to build. Just copy and paste the code. You will become a developer of iOS app.

Let's begin with how to confirm current date. The code is so simple as shown below.


Date()



And, for calculating 3 days after now, the code is like this.


var toDate = Calendar.current.date(byAdding: .day, value: 3, to: Date())!



The remaining date and time is substituted for the variable "toDate".


Next, let's see the function to calculate it.


func TimerFunction(from date: Date) -> String {
let calendar = Calendar(identifier: .gregorian)
let timeValue = calendar
.dateComponents([.day, .hour, .minute, .second], from: nowDate, to: setDate)
return String(format: "%02d days left - %02d:%02d:%02d",
timeValue.day!,
timeValue.hour!,
timeValue.minute!,
timeValue.second!)
}

From the struct Calendar components, it gets the detailed time and convert it to String. With this function, use like this.

@State var nowDate: Date = Date()
let setDate: Date
var timer: Timer {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {_ in
self.nowDate = Date()
}
}

var body: some View {
Text(TimerFunction(from: setDate))
.onAppear(perform: {self.timer
})
}



After starting up this app, it automatically calculate 3 days after now. It will be set as "setDate". On the other hand, the time of now changes as time goes by. The difference between "setDate" and now of "Date()" will be the remaining time you want.

In this example, the text shows "Birthday". But, you can change the "setDate" as you want. Please use this for your precious time.


To get the source code, check the comment of my YouTube

Back to Table List



 

2019年12月11日