检查日期何时过去 - Swift

Checking when a date has passed - Swift

好吧,标题几乎说明了一切。我想做的是检查日期何时过去。因此,例如,假设用户正在使用我的应用程序,然后他们在早上上床睡觉并检查我的应用程序。当我的应用程序打开时,我需要检查日期是否发生了变化。

此外,当应用程序终止或在后台运行时,我真的不需要知道这些信息。我只需要知道当应用程序 运行 并且用户实际与之交互时日期是否已更改。

注意:我查看了与此问题相关的其他 Stack Overflow 帖子,但其中 none 对我有所帮助。

实施观察

NSCalendarDayChangedNotification

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.

There are no guarantees about the timeliness of when this notification will be received by observers. As such, you should not rely on this notification being posted or received at any precise time.

The notification is posted through [NSNotificationCenter defaultCenter].

示例:

applicationDidFinishLaunching中添加

NSNotificationCenter.defaultCenter().addObserver(self, selector:"calendarDayDidChange:", name:NSCalendarDayChangedNotification, object:nil)

并实现方法

func calendarDayDidChange(notification : NSNotification)
{
   doSomethingWhenDayHasChanged()
}

或使用区块 API.

如果包含观察者的 class 不是应用程序委托 class 您可能会在某个时候删除观察者。

更新 vadian 对 Swift 5:

的回复
NotificationCenter.default.addObserver(self, selector:#selector(self.calendarDayDidChange(_:)), name:NSNotification.Name.NSCalendarDayChanged, object:nil)

并实现方法

@objc private func calendarDayDidChange(_ notification : NSNotification) {
    doSomethingWhenDayHasChanged()
}

如果您更新 UI,为防止崩溃,请使用此代码:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector:#selector(self.calendarDayDidChange(_:)), name:NSNotification.Name.NSCalendarDayChanged, object:nil)
}

@objc private func calendarDayDidChange(_ notification : NSNotification) {
    DispatchQueue.main.async { [weak self] in
        self?.setupLabel()
    }
}