背景
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
の通知タイミングで最前面のアプリケーションを調べれば良い.