MacOS App Local Notification Not Showing when testing with XCode

邮差的信 提交于 2020-12-31 10:44:35

问题


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


回答1:


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");
     }



回答2:


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
    }


来源:https://stackoverflow.com/questions/61185198/macos-app-local-notification-not-showing-when-testing-with-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!