How to find previous frontmost application in macOS

Issue #900

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)
Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation