UIPress.key is nil

Viewed 131

You may experience a problem where UIPress.key is nil when you are building a Catalyst app for macOS 11 Big Sur and trying to evaluate keyboard input. The code to reproduce the issue is following (in any UIViewController):

#if targetEnvironment(macCatalyst)
  override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
    //
    for press in presses {
      guard let key = press.key else { continue }
      NSLog("Key Pressed: %@", key.charactersIgnoringModifiers) // <-- will never be logged on Big Sur
    }
  }
 #endif

Running this with Catalina will work, but fails on Big Sur. I have opened a bug report to Apple since I thought this is a bug with Big Sur, but the answer to solve the problem was quite easy:

Simply implement the override for pressesBegan, and it starts to work. So, adding this:

override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
    //
    for press in presses {
      guard let key = press.key else { continue }
      NSLog("Key press began: %@", key.charactersIgnoringModifiers)
    }
 }

and the issue is solved.

That's it! I want to share it here, because you may suffer from same issue. But I have also a question to you: For me it's somewhat weird that I need to implement another override to make the desired override working. Do you know the reason here? Is this anywhere documented?

Thanks much.

1 Answers

Also important to note that if you callsuper.pressesEnded(presses, with: event) before accessing the value of UIPress.key then UIPress.key will be nil.

Related