2 // PeriodicNotifier.swift
5 // Created by Hori,Masaki on 2017/01/03.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
11 extension Notification.Name {
13 static let Periodic = Notification.Name("com.masakih.KCD.Notification.Periodic")
16 fileprivate extension Selector {
18 static let notifyIfNeeded = #selector(PeriodicNotifier.notifyIfNeeded(_:))
21 final class PeriodicNotifier: NSObject {
24 private let minutes: Int
26 init(hour: Int, minutes: Int) {
29 self.minutes = minutes
33 let nc = NotificationCenter.default
34 nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: notify)
35 nc.addObserver(forName: .NSSystemClockDidChange, object: nil, queue: nil, using: notify)
36 nc.addObserver(forName: .NSWorkspaceDidWake, object: nil, queue: nil, using: notify)
43 NotificationCenter.default.removeObserver(self)
46 private func notify(_ notification: Notification) {
51 @objc fileprivate func notifyIfNeeded(_ timer: Timer?) {
53 let now = Date(timeIntervalSinceNow: 0.0)
54 let unit: Set<Calendar.Component> = [.era, .year, .month, .day]
55 var currentDay = Calendar.current.dateComponents(unit, from: now)
56 currentDay.hour = hour
57 currentDay.minute = minutes
59 if let notifyDate = Calendar.current.date(from: currentDay),
60 now.compare(notifyDate) == .orderedDescending {
63 NotificationCenter.default.post(name: .Periodic, object: self)
66 if let v = timer?.isValid, v {
71 guard let nextNotifyDate = Calendar.current.date(from: currentDay)
72 else { fatalError("Can not create time of notify") }
74 let nextNotifyTime = nextNotifyDate.timeIntervalSinceNow + 0.1
75 Timer.scheduledTimer(timeInterval: nextNotifyTime,
77 selector: .notifyIfNeeded,