Swift 比较时间的快速循环

Swift 比较时间的快速循环,swift,loops,while-loop,cycle,Swift,Loops,While Loop,Cycle,我有一个时间表和当前时间。我应该写一个比较时间的循环。当计划时间等于当前时间时,周期应打印或发送通知 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: D

我有一个时间表和当前时间。我应该写一个比较时间的循环。当计划时间等于当前时间时,周期应打印或发送通知

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")
    }
}

这不是一种很好的工作方式,但这里对代码进行了一些修改:

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)
}
您只获得一次当前时间,因此
res==schedule
永远不会为真。在字符串值中使用不同的格式。您的字符串是
hh.mm.ss
,格式化程序是
hh.mm

编辑

要做到这一点,你应该使用定时器。首先获取时间间隔,然后将其作为计时器传递:

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)

res
将永远不会等于
schedule
,因为它们的格式不同,并且两个值都不会更改。但它们都是字符串格式,添加了以下内容:
print(res)
。请注意它与
计划的不同之处。这会阻塞CPU而无法真正工作。在每次迭代中,您都必须睡眠一段时间。