Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
12
Help us understand the problem. What is going on with this article?
@hikipuro

(Swift) Macbookでフタを閉じた瞬間、開いた瞬間にイベントを受け取る

More than 5 years have passed since last update.

Macbookのフタ閉じた時のイベントって取れるの?

気になったので調べてみました。
簡単にコピペで使えるように、コードを貼ってみます。
ObjCのかたは、下の参考リンクのところからジャンプ先を見てみてください。

まだ実際、軽くしか動作確認できていないので、もしかしたらちゃんと動かないかもです。

ViewController.swift
import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // 通知を受け取ることができるように設定する
        let notificationCenter = NSWorkspace.sharedWorkspace().notificationCenter;
        notificationCenter.addObserver(
            self,
            selector: #selector(receiveSleepNote(_:)),
            name: NSWorkspaceWillSleepNotification,
            object: nil
        )
        notificationCenter.addObserver(
            self,
            selector: #selector(receiveWakeNote(_:)),
            name: NSWorkspaceDidWakeNotification,
            object: nil
        )
    }

    // スリープされた瞬間に通知を受け取る
    func receiveSleepNote(n:NSNotification) {
        print("receiveSleepNote: ", n.name)
    }

    // スリープ解除された瞬間に通知を受け取る
    func receiveWakeNote(n:NSNotification) {
        print("receiveWakeNote: ", n.name)
    }

}

参考URL

12
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
hikipuro

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
12
Help us understand the problem. What is going on with this article?