0

I am trying to send local notifications from my Mac app(written in swift using Cocoa) So far I've written this function

func scheduleNotification() {
        let content = UNMutableNotificationContent()
        content.title = "Test"
        content.body = "This is a test"
        content.sound = .default
        content.badge = 1
        let now = Date()
        let int = timePicker.dateValue.timeIntervalSince(now)
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: int, repeats: false)
        let request = UNNotificationRequest(identifier: "Test notification", content: content, trigger: trigger)
        center.add(request) { (err) in
            if err == nil {
                print("Success")
            }
        }

    }

But for some reason it doesn't show a banner or anything in the Notification Center. Is something wrong with my code or something else causing this? (I checked and the app has the permission to send notifications) And also, what is the equivalent on macOS for the UIApplication.shared.applicationBadgeNumber = 0 on iOS?

David
  • 61
  • 3

2 Answers2

0

If app is on foreground, you have to use UNUserNotificationCenterDelegate.

UNUserNotificationCenter.current().delegate = self

Firstly notify that delegate in viewDidLoad.

extension ViewController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    return completionHandler([.alert, .sound, .badge])
}

}

And after you can use delegate like that. Check this out more information this post -> Local Notifications

0

So, as it turns out asking for permission is mandatory in MacOS Catalina, that was all that missing.

David
  • 61
  • 3