generate a macos notification in swift

To generate a MacOS notification in Swift, you can use either the NSUserNotificationCenter or UserNotifications framework depending on the version of MacOS you are targeting.

Using NSUserNotificationCenter

main.swift
import Foundation
import AppKit

let notification = NSUserNotification()
notification.title = "My Notification"
notification.informativeText = "This is a notification from my Swift app"

let center = NSUserNotificationCenter.default

center.deliver(notification)
263 chars
11 lines

Using UserNotifications

main.swift
import Foundation
import UserNotifications

let content = UNMutableNotificationContent()
content.title = "My Notification"
content.body = "This is a notification from my Swift app"
content.sound = UNNotificationSound.default

// Set the notification time for 5 seconds from now
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false)

// Create the request object for the notification
let request = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger)

// Add the request to the notification center
let center = UNUserNotificationCenter.current()
center.add(request)
629 chars
18 lines

Both methods allow you to customize the title, message, and sound of the notification as well as set a trigger for when the notification should be shown.

gistlibby LogSnag