swiftmacosnsusernotificationunusernotification

What's the Difference Between NSUserNotification and UNUserNotification in macOS?


I have the following lines of code to post a notification by clicking on the Test button.

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
        return true
    }
}

import Cocoa
import CloudKit

class HomeViewController: BasicViewController, NSUserNotificationCenterDelegate {
    override func viewDidLoad() {
    }

    @IBAction func testClicked(_ sender: NSButton) {
        let notification = MyNotificationDelegate()
        NSUserNotificationCenter.default.delegate = self
        notification.setNotification(title: "Test", message: "Test me if you can!")       
    }
}

import Cocoa

class MyNotificationDelegate: NSObject {
    func setNotification(title: String, message: String) {
        let notification: NSUserNotification = NSUserNotification()
        notification.title = title
        notification.informativeText = message
        NSUserNotificationCenter.default.deliver(notification)
    }
}

This code comes from this topic. It's NSUserNotification.

And I have seen this topic. It's UNUserNotification. Basically, what it does is the same as the above. So what's the difference between NSUserNotification and UNUserNotification? The only difference I see is that the latter lets you find out whether or not the user has allowed to post a notification.

Neither NSUserNotification or UNUserNotification lets the system show the notification if the application is at front. I wonder why?

Thanks.


Solution

  • NSUserNotification is now deprecated.

    A UNNotification object contains the initial notification request, which contains the notification's payload, and the date on which the notification was delivered.

    Don't create notification objects directly. When handling notifications, the system delivers notification objects to your UNUserNotificationCenterDelegate object. The UNUserNotificationCenter object also maintains the list of notifications that were previously delivered, and you use the getDeliveredNotifications(completionHandler:) method to retrieve those objects.

    Use UNUserNotifaction instead