2 // TimeSignalNotifier.swift
5 // Created by Hori,Masaki on 2017/01/21.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
12 static let fire = #selector(TimeSignalNotifier.fire(_:))
15 class TimeSignalNotifier: NSObject {
16 let udController: NSUserDefaultsController = NSUserDefaultsController.shared()
21 self.bind(#keyPath(notifyTimeBeforeTimeSignal),
23 withKeyPath: "values.notifyTimeBeforeTimeSignal")
26 self.unbind(#keyPath(notifyTimeBeforeTimeSignal))
29 dynamic var notifyTimeBeforeTimeSignal: Int = 0 {
30 didSet { registerTimer() }
34 func fire(_ timer: Timer) {
35 defer { registerTimer() }
36 if !UserDefaults.standard.notifyTimeSignal { return }
39 let cal = Calendar.current
40 let minutes = cal.component(.minute, from: now)
42 if (59 - minutes) > notifyTimeBeforeTimeSignal { return }
44 let notification = NSUserNotification()
45 let hour = cal.component(.hour, from: now)
46 let format = NSLocalizedString("It is soon %zd o'clock.",
47 comment: "It is soon %zd o'clock.")
48 notification.title = String(format: format, hour + 1)
49 notification.informativeText = notification.title
50 if UserDefaults.standard.playNotifyTimeSignalSound {
51 notification.soundName = NSUserNotificationDefaultSoundName
53 NSUserNotificationCenter.default.deliver(notification)
56 private func registerTimer() {
60 let cal = Calendar.current
61 var comp = cal.dateComponents([.year, .month, .day, .hour], from: now)
62 let minutes = cal.component(.minute, from: now)
63 if minutes + notifyTimeBeforeTimeSignal >= 60 {
64 comp.hour = comp.hour.map { $0 + 1 }
66 comp.minute = 60 - notifyTimeBeforeTimeSignal
67 guard let notifyDate = cal.date(from: comp)
68 else { return print("Can not create notify date") }
69 timer = Timer.scheduledTimer(timeInterval: notifyDate.timeIntervalSinceNow,