检查一天的变化 - 时区调整

Checking for a Day Change - Timezone Adjusted

我刚刚尝试创建一些代码(粘贴在下面)来检查一天的变化。但是,现在I'm reading有一个特殊的日期更改功能。

NSCalendarDayChangedNotification

显然它适用于 iOS8 及更高版本。但是人们一直在使用短语 "you can listen to it"... 就好像使用该功能就像调到广播电台一样。我查了一下,上次 WWDC 提供了一些相关代码的演示文稿:

Reacting to the Change of Day • You may want to run some code when the day changes NSCalendarDayChangedNotification • Example

noteCenter = [NSNotificationCenter defaultCenter];
observer = [noteCenter addObserverForName:NSCalendarDayChangedNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
// your code here
}];

我的问题

不过,我找到的 PDF 并没有说明其他内容。所以我的问题是这个功能是如何工作的? PDF 使它看起来真的就是这么简单,将代码粘贴进去,我就完成了。真的吗?它会根据时区进行调整吗?我必须启用它引用的这个通知中心吗?

我的代码(不确定是否有效):

    //Find out if it's a new day
    let lastDateUsed_NSDefault = NSUserDefaults.standardUserDefaults()
    if let endOf_LastDateUsed = lastDateUsed_NSDefault.objectForKey("lastDateUsed") as! NSDate! {
        print("Success! NSUserDefault key: 'lastDateUsed' returned \(endOf_LastDateUsed)")
        //Check if the day has changed

        let calendar = NSCalendar.currentCalendar()
        let startOfToday = calendar.startOfDayForDate(now)

        if endOf_LastDateUsed.compare(startOfToday) == NSComparisonResult.OrderedAscending {
            //endOf_LastDateUsed is greater than startOfToday.
            print("Do nothing! Last date used must have been today!")
        } else if endOf_LastDateUsed.compare(startOfToday) == NSComparisonResult.OrderedAscending {
            //Day has changed. Run alert.


            //Save "endOfToday" date value to NSDefault
            let endOfToday = startOfToday.dateByAddingTimeInterval(24 * 60 * 60)
            NSUserDefaults.standardUserDefaults().setObject(endOfToday, forKey:"lastDateUsed")
            print("Time stored in NSDefault: \(endOfToday)")
        }

    }
    else {
        print("Failure! NSUserDefault key: 'lasteDateUsed' returned nothing. No record.")
        //First time user - Set end of today
        let calendar = NSCalendar.currentCalendar()
        let startOfToday = calendar.startOfDayForDate(now)
        print("startOfToday: \(startOfToday)")
        let endOfToday = startOfToday.dateByAddingTimeInterval(24 * 60 * 60)
        //Store
        NSUserDefaults.standardUserDefaults().setObject(endOfToday, forKey:"lastDateUsed")

        print("Time stored in NSDefault: \(endOfToday)")
    }

documentation(诚然,这比我希望的要难一些)相当清楚:

Posted whenever the calendar day of the system changes, as determined by the system calendar, locale, and time zone.

所以是的,它应该适当地处理夏令时的变化,因为它知道时区。我不知道如何启用通知中心,但通过调整设备上的系统时钟或时区并查看会发生什么,应该很容易进行测试。

(文档中没有清楚的是,如果通过手动干预更改日期,是否会触发此事件,例如通过更改系统时间或时区直接更改日期的方式。值得您尝试一下。)