Search code examples
swiftmacosappkit

How can I detect if app was launched by user clicking notification on macOS now that launchUserNotificationUserInfoKey has been deprecated?


I used to use NSUserNotification’s launchUserNotificationUserInfoKey to detect if app was launched by user clicking notification on macOS.

class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
  var notificationCenterLaunch = false
  func applicationDidFinishLaunching(_ notification: Notification) {
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (allowed, error) in
      // Check if notifications are allowed
      if allowed {
        // Check if app was launched by clicking on notification
        if notification.userInfo?[NSApplication.launchUserNotificationUserInfoKey] != nil {
          self.notificationCenterLaunch = true
        }
      }
    }
  }
}

Given NSUserNotification has been deprecated, I refactored codebase to use UNUserNotification, but now, launchUserNotificationUserInfoKey is no longer present in applicationDidFinishLaunching’s notification object.

How can I detect if app was launched by user clicking notification on macOS?


Solution

  • I believe this issue is caused by a bug in macOS Big Sur 11.6 rather than launchUserNotificationUserInfoKey been deprecated (which I likely assumed by mistake)?

    Everything works as expected in macOS Big Sur 11.6.1 or macOS Monterey.