LoginSignup
0

More than 5 years have passed since last update.

Swift:macのスリープ/復帰の通知を受ける

Posted at

はじめに

macOSアプリ作成時,アニメーション処理をスリープした時に一時時に止めたくなった.
Swiftでのスリープと復帰の通知の受け方を調べた.

参考:Mac OS Xでスリープ、復帰時の通知を扱う

ソース

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")
    }

}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0