David
David

Reputation: 61

Why aren't local notifications showing up on Mac?

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?

Upvotes: 0

Views: 518

Answers (2)

David
David

Reputation: 61

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

Upvotes: 0

Yavuz Aytekin
Yavuz Aytekin

Reputation: 53

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

Upvotes: 0

Related Questions