Home > Software design >  Notification does not trigger userNotificationCenter on macOS Big Sur 11.6
Notification does not trigger userNotificationCenter on macOS Big Sur 11.6

Time:10-28

When I run app using terminate argument (set using “Product“ / “Scheme” / “Edit Scheme…” / “Run” / “Arguments” / “Argument Passes On Launch”), a notification appears in macOS Notification Centre and app terminates.

#testapp application did finish launching
#testapp terminate mode enabled
#testapp terminating…

So far, so good… Expected.

When I click notification, app launches but userNotificationCenter is not triggered (I don’t see #testapp notification triggered in Console app, but I see following).

#testapp application did finish launching
#testapp terminating…

Not normal right? How can I fix this?

I am starting to think that this is a Big Sur bug in version 11.6.

Everything works fine on Big Sur version 11.4 (M1) and 11.5 (Intel).

Thanks for helping out!

//
//  AppDelegate.swift
//  Test
//
//  Created by Sun Knudsen on 2021-10-22.
//

import Cocoa
import UserNotifications

@main
class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
  func showNotification(){
    let content = UNMutableNotificationContent()
    content.body = "Hello"
    let request = UNNotificationRequest(
      identifier: UUID().uuidString,
      content: content,
      trigger: nil
    )
    UNUserNotificationCenter.current().add(request)
  }
  
  func terminate() -> Void {
    DispatchQueue.main.async {
      NSApp.terminate(self)
    }
  }
  
  func applicationDidFinishLaunching(_ notification: Notification) {
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (allowed, error) in
      NSLog("#testapp application did finish launching")
      if CommandLine.arguments.indices.contains(1) && CommandLine.arguments[1] == "terminate" {
        NSLog("#testapp terminate mode enabled")
        self.showNotification()
        self.terminate()
      } else {
        DispatchQueue.main.asyncAfter(deadline: .now()   1.0) {
          self.terminate()
        }
      }
    }
  }

  func applicationWillTerminate(_ aNotification: Notification) {
    NSLog("#testapp terminating…")
  }
  
  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
  ) {
    NSLog("#testapp notification triggered")
    self.terminate()
    completionHandler()
  }
}

Test app available on GitHub at https://github.com/sunknudsen/test-app.

CodePudding user response:

This issue is caused by a bug in macOS Big Sur 11.6.

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

  • Related