I want to create a 24 hour sale timer and display it inside button. I am using this code but don't know how to stop this timer.
This is my code. In this example I use 35 second to test this faster:
class SLTimer {
func timeLeftExtended(date: Date) -> String {
let cal = Calendar.current
let now = Date()
let calendarUnits:NSCalendar.Unit = [NSCalendar.Unit.hour, NSCalendar.Unit.minute, NSCalendar.Unit.second]
let components = (cal as NSCalendar).components(calendarUnits, from: now, to: date, options: [])
let fullCountDownStr = "\(components.hour!.description) : " +
"\(components.minute!.description) : " +
"\(components.second!.description)"
return fullCountDownStr
}
@objc func updateCountDown() -> String
{
var timeString = ""
let newDate = Calendar.current.date(byAdding: .second, value: 35, to: Date())
if let waitingDate = UserDefaults.standard.value(forKey: "waitingDate") as? Date {
if let diff = Calendar.current.dateComponents([.second], from: newDate!, to: Date()).second, diff > 35 {
timeString = "stop"
} else {
timeString = self.timeLeftExtended(date: waitingDate)
}
} else {
UserDefaults.standard.set(newDate, forKey: "waitingDate")
timeString = self.timeLeftExtended(date: newDate!)
}
return timeString
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.start), userInfo: nil, repeats: true)
}
@objc func start() {
saleButton.setTitle("\(SLTimer().updateCountDown())", for: .normal)
}
}
it doesn't call this lines after 35 seconds:
if let diff = Calendar.current.dateComponents([.second], from: newDate!, to: Date()).second, diff > 35 {
timeString = "stop"
}