OSDN Git Service

必要のない処理を削除
[kcd/KCD.git] / KCD / PeriodicNotifier.swift
1 //
2 //  PeriodicNotifier.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/01/03.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 extension Notification.Name {
12     
13     static let Periodic = Notification.Name("com.masakih.KCD.Notification.Periodic")
14 }
15
16 final class PeriodicNotifier: NSObject {
17     
18     private let hour: Int
19     private let minutes: Int
20     
21     init(hour: Int, minutes: Int) {
22         
23         self.hour = hour
24         self.minutes = minutes
25         
26         super.init()
27         
28         let nc = NotificationCenter.default
29         nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: notify)
30         nc.addObserver(forName: .NSSystemClockDidChange, object: nil, queue: nil, using: notify)
31         nc.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: nil, using: notify)
32         
33         notifyIfNeeded(nil)
34     }
35     
36     private func notify(_ notification: Notification) {
37         
38         notifyIfNeeded(nil)
39     }
40     
41     @objc fileprivate func notifyIfNeeded(_ timer: Timer?) {
42         
43         let now = Date(timeIntervalSinceNow: 0.0)
44         let unit: Set<Calendar.Component> = [.era, .year, .month, .day]
45         var currentDay = Calendar.current.dateComponents(unit, from: now)
46         currentDay.hour = hour
47         currentDay.minute = minutes
48         
49         if let notifyDate = Calendar.current.date(from: currentDay),
50             now.compare(notifyDate) == .orderedDescending {
51             
52             currentDay.day? += 1
53             NotificationCenter.default.post(name: .Periodic, object: self)
54         }
55         
56         if let v = timer?.isValid, v {
57             
58             timer?.invalidate()
59         }
60         
61         guard let nextNotifyDate = Calendar.current.date(from: currentDay) else { fatalError("Can not create time of notify") }
62         
63         let nextNotifyTime = nextNotifyDate.timeIntervalSinceNow + 0.1
64         Timer.scheduledTimer(timeInterval: nextNotifyTime,
65                              target: self,
66                              selector: #selector(PeriodicNotifier.notifyIfNeeded(_:)),
67                              userInfo: nil,
68                              repeats: false)
69     }
70 }