How to handle UIPhysicalKeyboardEvent?

I'm trying to improve our application to receive and handle events from a bluetooth keyboard. To intercept incoming events I use sendEvent: method. But I get a different event type for a different key. For example when I press 'Esc' key I get an event type is UIEventTypePresses (and event is a instance of UIPressesEvent class) but when I press 'ArrowUp' key I get an event type is 4 (there is no enum value for that number) and event is a instance of UIPhysicalKeyboardEvent class. In the first case I found a documentation of UIPressesEvent and I can implement handler for it. But for the second case I didn't find any documentations of UIPhysicalKeyboardEvent nether in the online documentation nor in the Xcode help. How can UIPhysicalKeyboardEvent events be handled? Is the any documentation for that?

My target OS is tvOS 17.1

Replies

You should not be intercepting events using the sendEvent(_:) method. Instead, you should use the publicly available API for handling press events using pressesBegan/pressesEnded.

Both UIPhysicalKeyboardEvent and the eventType properties are also low-level system-defined structures that you should not be referencing because of their ambiguous and platform-specific nature. Instead, if you need to know precisely when an event began and ended and which key it's associated with, you should consult the UIKey object plumbed via UIPress. UIKey provides a keyCode property, which is a stable, platform-agnostic representation of precisely which key was pressed in the event.

Keep in mind that the low-level pressesBegan/pressesEnded APIs are only for actually intercepting events in the responder chain, and are specifically designed for cases where developers need to know when a key is pressed and released. In most cases, the UIKeyCommand API is a better solution for instances when your app only needs to respond to a keyboard shortcut (like pressing "Space" to play/pause, or other shortcuts involving the command key). Using this API will also allow your shortcuts to be visible in the menu bar on macOS (when running with Mac Catalyst) and the keyboard command HUD (visible when holding the command key) on iPadOS.