はじめに
macOSアプリ作成時,アニメーション処理をスリープした時に一時時に止めたくなった.
Swiftでのスリープと復帰の通知の受け方を調べた.
ソース
AppDelegateに以下のように通知を登録する.
AppDelegate.swift
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
private let nc = NSWorkspace.shared.notificationCenter
func applicationDidFinishLaunching(_ aNotification: Notification) {
setNotifications()
}
func applicationWillTerminate(_ aNotification: Notification) {
}
func setNotifications() {
nc.addObserver(self, selector: #selector(AppDelegate.receiveSleepNote),
name: NSWorkspace.willSleepNotification, object: nil)
nc.addObserver(self, selector: #selector(AppDelegate.receiveWakeNote),
name: NSWorkspace.didWakeNotification, object: nil)
}
@objc func receiveSleepNote() {
Swift.print("go to sleep")
}
@objc func receiveWakeNote() {
Swift.print("wake up")
}
}