Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MacOS App Local Notification Not Showing when testing with XCode

I have tried to add a banner notification generator to my macOS swift app and the banner does not appear when test running in XCode and neither are there any new notifications visible in the notification centre. Other apps on my computer are generating notifications regularly. What have I missed? I have granted permission when requested

My app delegate is as follows

class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

    @IBOutlet weak var mainMenu: NSMenu!

    func applicationDidFinishLaunching(_ aNotification: Notification)
        {
         NSUserNotificationCenter.default.delegate = self ;
        }

    func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool
        {
        return true
        }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

On app startup I run the following method and I see the console line "Notifications allowed"

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge, .provisional])
    { granted, error in
    if error != nil
       {
       print ("Request notifications permission Error");
       };
   if granted
       {
       self.allowNotifications = true ;
       print ("Notifications allowed");
       }
   else
       {
       self.allowNotifications = false ;
       print ("Notifications denied");
       };
 }

The method I have added to my ViewController is as follows and I have tested that the print statement at the end is reached

func generateNotification (summary:String, sound:String, title:String , body:String)
    {
    let notification = NSUserNotification()
    if !allowNotifications {return};
    notification.title = summary ;
    notification.subtitle = title ;
    notification.informativeText = body ;
    if (sound == "YES") {notification.soundName = NSUserNotificationDefaultSoundName};
    NSUserNotificationCenter.default.deliver (notification);
    print ("notification generated");
    };

Please help me

like image 468
Steve Brooker Avatar asked Oct 21 '25 04:10

Steve Brooker


2 Answers

I believe that my problem here was asking permission to use UNUserNotification and then using NSUserNotification to create the notification itself, which of course I had not requested permission to use. Requesting permission is now mandatory in Catalina (and perhaps it was in earlier versions of macOS as well.)

So I replaced the generateNotification function with the following and it all works correctly.

let notificationCenter = UNUserNotificationCenter.current();
notificationCenter.getNotificationSettings
   { (settings) in
   if settings.authorizationStatus == .authorized
       {
       //print ("Notifications Still Allowed");
       // build the banner
       let content = UNMutableNotificationContent();
       content.title = summary ;
       content.body = title ;
       if sound == "YES" {content.sound = UNNotificationSound.default};
       // could add .badge
       // could add .userInfo

       // define when banner will appear - this is set to 1 second - note you cannot set this to zero
      let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false);

       // Create the request
       let uuidString = UUID().uuidString ; 
       let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger);

      // Schedule the request with the system.
      notificationCenter.add(request, withCompletionHandler:
         { (error) in
         if error != nil
             {
             // Something went wrong
             }
          })
      //print ("Notification Generated");
     }
like image 96
Steve Brooker Avatar answered Oct 23 '25 18:10

Steve Brooker


In addition to the answer of Steve Brooker, for me it was working only when I set the delegate for UNUserNotificationCenter. I've spent half a day trying to make it work with NSUserNotificationCenter / NSUserNotification without any success. So thanks for your answer, Steve :) My working version is as follows:

    if #available(OSX 10.14, *) {
        UNUserNotificationCenter.current().delegate = self // must have delegate, otherwise notification won't appear
        UNUserNotificationCenter.current()
          .requestAuthorization(options: [.alert, .sound, .badge]) {
            [weak self] granted, error in
              
            print("Permission granted: \(granted)")
            guard granted else { return }

            let sound = "NO"
            let notificationCenter = UNUserNotificationCenter.current()
            notificationCenter.getNotificationSettings
               { (settings) in
                if settings.authorizationStatus == .authorized {
                    //print ("Notifications Still Allowed");
                    // build the banner
                    let content = UNMutableNotificationContent();
                    content.title = "summary" ;
                    content.body = "title" ;
                    if sound == "YES" {content.sound =  UNNotificationSound.default};
                    // could add .badge
                    // could add .userInfo

                    // define when banner will appear - this is set to 1 second - note you cannot set this to zero
                    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false);

                    // Create the request
                    let uuidString = UUID().uuidString ;
                    let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger);

                    // Schedule the request with the system.
                    notificationCenter.add(request, withCompletionHandler:
                        { (error) in
                        if error != nil
                            {
                                // Something went wrong
                            }
                        })
                    //print ("Notification Generated");
                }
            }
        }
    } else {
        // Fallback on earlier versions
    }
like image 25
nickeyzzz Avatar answered Oct 23 '25 17:10

nickeyzzz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!