使用 XCode 进行测试时 MacOS 应用程序本地通知未显示

MacOS App Local Notification Not Showing when testing with XCode

我尝试将横幅通知生成器添加到我的 macOS swift 应用程序,但在 XCode 中测试 运行ning 时横幅没有出现,也没有任何新通知在通知中心可见。我电脑上的其他应用程序会定期生成通知。我错过了什么?我已按要求授予权限

我的app委托如下

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
    }

在应用程序启动时,我 运行 使用以下方法,我看到了控制台行 "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");
       };
 }

我添加到我的ViewController的方法如下,我测试到了最后的打印语句

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

请帮帮我

我认为我的问题是请求使用 UNUserNotification 的许可,然后使用 NSUserNotification 创建通知本身,当然我没有请求使用许可。现在在 Catalina 中请求权限是强制性的(也许在早期版本的 macOS 中也是如此。)

所以我用下面的代码替换了 generateNotification 函数,它一切正常。

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

除了 Steve Brooker 的回答之外,对我来说,只有当我为 UNUserNotificationCenter 设置委托时它才有效。我花了半天时间试图让它与 NSUserNotificationCenter / NSUserNotification 一起工作,但没有成功。所以谢谢你的回答,史蒂夫 :) 我的工作版本如下:

    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
    }