Search code examples
swiftloopswhile-loopcycle

Swift cycle which compare times


i have a schedule time and current time. I should write cycle which compare times. Cycle should print or send notification when schedule time equals to current time.

var schedule : String = "12.22.00"
let formatter = DateFormatter()
formatter.dateFormat = "HH.mm.ss"
let calendar = Calendar.current
let minutesago = calendar.date(byAdding: .minute, value: +2, to: Date())!
let res = formatter.string(from: minutesago)

while true {
    if res == schedule {
        notificate()
        print("isequl")
    }
}

Solution

  • This is not a good way to work but here is little modification in your code:

    var schedule : String = "12.19.00"
    let formatter = DateFormatter()
    formatter.dateFormat = "HH.mm.ss"
    while true {
        let date = Date()
        let res = formatter.string(from: date)
        if res == schedule
        {
            print("isequl")
            break
        }
        sleep(10000)
    }
    

    You are getting current time only once so res == schedule will never be true. And you are using different format in then your string value. Your string is hh.mm.ss and formatter is hh.mm

    EDIT

    To do that you should use timer. First get time interval and then pass it in Timer as:

    let date = Date().addingTimeInterval(interval)
    let timer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)
    RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)