我想每天午夜更新状态。但定时器是按时间间隔的。如何按天设置间隔
var timer = Timer()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
// called every time interval from the timer
func timerAction() {
}
最佳答案
不需要计时器。观察通知
static let NSCalendarDayChanged: NSNotification.Name
Posted whenever the calendar day of the system changes, as determined by the system calendar, locale, and time zone. This notification does not provide an object.
If the the device is asleep when the day changes, this notification will be posted on wakeup. Only one notification will be posted on wakeup if the device has been asleep for multiple days.
NotificationCenter.default.addObserver(self, selector:#selector(calendarDayDidChange), name:.NSCalendarDayChanged, object:nil)
...
func calendarDayDidChange()
{
print("day did change")
}
或者使用基于闭包的 API
NotificationCenter.default.addObserver(forName: .NSCalendarDayChanged, object: nil, queue: .main) { _ in
print("day did change")
}
或合并
var subscription : AnyCancellable?
subscription = NotificationCenter.default.publisher(for: .NSCalendarDayChanged)
.sink { _ in print("day did change") }
或者使用 async/await (Swift 5.5+)
Task {
for await _ in NotificationCenter.default.notifications(named: .NSCalendarDayChanged) {
print("day did change")
}
}
关于swift - 每天午夜运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44973888/