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
2
Help us understand the problem. What is going on with this article?
@Kyome

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

More than 1 year has passed since last update.

背景

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
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
Kyome
火星に住む犬です。 趣味でmacOS アプリを開発しています。

Comments

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