Search code examples
swiftswiftuigamecontroller

GameController button support in the background


I am using the GameController framework to build a SwiftUI macOS app, that can detect when buttons on an Xbox Controller are pressed. When the view is the foreground ( active window present ), I can monitor which button is pressed. However, when the app goes to background ( I click on a different app on my desktop to steal the view ), I can no longer monitor which button is pressed. A post from 2 years ago, https://developer.apple.com/forums/thread/668828 , mentions that this is not possible.

There is, apparently, no way to use GameController data in the background — I guess for security reasons. So if like me you were blaming app nap or trying to allow input monitoring for your app, there is no reason to search that path.

Given that so much time has passed, I wanted to see if a solution now exists. For ex, I want to execute something of this nature when the macOS app is not in the foreground:

if let controller = GCController.controllers().first, let pad = controller.extendedGamepad {
    buttons = pad.allButtons.compactMap { $0 }
    for button in buttons {
        if button.isPressed {
            print("## pressed... \(button.debugDescription)")
        }
    }
}

Solution

  • Maybe this can help you:

    shouldMonitorBackgroundEvents
    

    A Boolean value that indicates whether the app needs to respond to controller events when it isn’t the frontmost app.

    If false, and the app isn’t in the foreground, the framework doesn’t forward any input from the game controller until the app becomes the frontmost.

    Important:

    In macOS 11.3 and later, the default value for this property is false. Prior to macOS 11.3, the default value is true. In iOS and tvOS, the framework ignores this property.

    Source: Apple Docs