我的应用程序应该在时间发生变化时执行操作(每分钟,而不是每秒)。我实现此目的的方法是创建一个 Timer 对象,如下所示:
var timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
虽然这种方式有效,但看起来不太专业,因为应用程序不会在时间变化时准确执行更新,而是取决于创建对象的精确时刻。例如,如果 Timer
对象是在 10:10:30 创建的,那么更新只会在分钟更改后 30 秒执行。
有什么方法可以让我知道手机上的时间分钟发生变化吗?
提前致谢!
最佳答案
您可以安排第一个计时器在特定时间触发,该时间可以是下一轮的分钟。这是一个示例(复制并粘贴到 Playground ):
import PlaygroundSupport
import Foundation
let cal = NSCalendar.current
var comps = cal.dateComponents([.era, .year, .month, .day, .hour, .minute], from: Date())
comps.minute = comps.minute! + 1
let nextMinute = cal.date(from: comps)
let timer = Timer(fire: nextMinute!, interval: 60, repeats: true) { _ in
print("Minute change")
}
RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
PlaygroundPage.current.needsIndefiniteExecution = true
请注意,如果应用程序在后台运行,计时器将不会触发。
关于ios - Swift 3 时间变化时如何执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41757523/