2

I would like to know with Swift, if my macOS app is running in the background of in foreground.

I found different ways (for example here: Is there any way to check if iOS app is in background? ) related to iOS apps, but not for modern macOS.

It would be great if there was also for macOS a way similar to this one:

   let state = NSApplication.applicationState
   if state == .background { // doesn't work
    // do something here
   }
Cue
  • 2,952
  • 3
  • 33
  • 54
  • 1
    Did you check the properties of [NSApplication](https://developer.apple.com/documentation/appkit/nsapplication?language=objc)? – Willeke May 06 '19 at 22:18

1 Answers1

4

I found this way:

    let application = NSApplication.shared
    let state = application.isActive

    if state {
        print("app in foreground")
    }
Cue
  • 2,952
  • 3
  • 33
  • 54