I am trying to display banner notification on macOS swift app and the banner does not appear when running debug build in Xcode neither any new notification related my app is visible in the notification center whereas other app notification are being displayed regularly. What have I missed? I have granted permission when requested
My Appdelegate file
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification)
{
NSUserNotificationCenter.default.delegate = self
}
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool
{
return true
}
On app startup I try to request premission from the user
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge, .provisional])
{ allowed, error in
if allowed{
print ("Notifications allowed");
}else{
print ("Notifications denied")
}
}
And this the code for triggering the notification
let notification = NSUserNotification()
notification.title = "test"
notification.subtitle = "Test notification"
notification.informativeText = "this the test notification"
NSUserNotificationCenter.default.deliver(notification)
What am i missing here.
I am trying to push local notification in macOS swift app.
2
Answers
There are a few things you might be missing:
You are using NSUserNotification which is deprecated in macOS 10.14 and later. You should use NSUserNotificationCenter instead.
You are trying to use NSUserNotificationCenter with NSUserNotification which is not correct.
NSUserNotificationCenter is used to display notifications, and NSUserNotification is used to create the content of the notification.
Here is the correct way to do it:
This will not work because NSUserNotificationCenter does not support delivering notifications directly. You need to schedule the notification to be delivered at a later time.
Here is how you can do it:
This will schedule the notification to be delivered. However, this will not work if the user has not granted permission to your app to display notifications. You need to request permission first:
This will request permission to display notifications. If the user grants permission, you can schedule the notification to be delivered.
Remember to handle the case where the user denies permission. In this case, you should not schedule the notification.
Also, remember to handle the case where the user has granted permission but has not allowed notifications to be displayed in the notification center. In this case, you should not schedule the notification.
For macOS version 10.14 and above please use
UNUserNotificationCenter
instead ofNSUserNotification
For delegate on macOS 10.14 and above
For delegate on macOS lower than 10.14
For triggering the notification on macOS 10.14 and above
For triggering the notification on macOS lower than 10.14
Your permission code is correct.