При тестировании с XCode локальное уведомление приложения MacOS не отображается - PullRequest
1 голос
/ 13 апреля 2020

Я попытался добавить генератор уведомлений о баннерах в мое приложение MacOS Swift, и баннер не отображается при тестовом запуске в XCode, и в центре уведомлений не отображаются новые уведомления. Другие приложения на моем компьютере регулярно генерируют уведомления. Что я пропустил? Я получил разрешение при запросе

Мой делегат приложения выглядит следующим образом

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
    }

При запуске приложения я запускаю следующий метод и вижу строку консоли «Уведомления разрешены»

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, выглядит следующим образом, и я проверил, что оператор print в конце достигнут

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

Пожалуйста, помогите мне

1 Ответ

0 голосов
/ 13 апреля 2020

Я полагаю, что моей проблемой здесь было получение разрешения на использование 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");
     }
...