LoginSignup
2
3

More than 5 years have passed since last update.

Swift:最前面にあるアプリケーションが何かを監視する

Posted at

背景

macOS向け常駐アプリを作っていて,最前面(frontmost)にあるアプリが何であるかを監視し続けたくなった.これまでタイマーを使って定期的に最前面のNSWindowのオーナーを調べるという方法を取っていたが,最前面のアプリが切り替わったタイミングのみで監視対象の更新を行いたかった.

実装

Appdelegate.swift
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) { 
        NSWorkspace.shared.notificationCenter.addObserver(self,
                                                          selector: #selector(check(_:)),
                                                          name: NSWorkspace.didActivateApplicationNotification,
                                                          object: nil)
    }

    @objc func check(_ notification: NSNotification) {
        guard let name = NSWorkspace.shared.frontmostApplication?.localizedName else {
            return
        }
        Swift.print(name)
    }
}

NSWorkspace.didActivateApplicationNotificationの通知タイミングで最前面のアプリケーションを調べれば良い.

2
3
0

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
2
3