onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to find previous frontmost application in macOS #900

Open onmyway133 opened 1 year ago

onmyway133 commented 1 year ago

Listen to didActivateApplicationNotification and check that it is not our app

NSWorkspace.shared.notificationCenter
    .publisher(for: NSWorkspace.didActivateApplicationNotification)
    .sink(receiveValue: { [weak self] note in
        guard
            let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
            app.bundleIdentifier != Bundle.main.bundleIdentifier
        else { return }

        self?.frontMostApp = app
    })
    .store(in: &bag)