Post

Replies

Boosts

Views

Activity

Questions about using the "UserNotification framework"
In macOS, how can I use UnmutableNotificationContent notifications to prevent the main window from activating when clicking the notification? code: import Cocoa import UserNotifications // Mandatory import for notification functionality class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Automatically request permissions and send a test notification when the view loads sendLocalNotification() } /// Core method to send a local notification func sendLocalNotification() { let notificationCenter = UNUserNotificationCenter.current() // 1. Request notification permissions (Mandatory step; user approval required) notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] isGranted, error in guard let self = self else { return } // Handle permission request errors if let error = error { print("Permission request failed: \(error.localizedDescription)") return } // Exit if user denies permission if !isGranted { print("User denied notification permissions; cannot send notifications") return } // 2. Construct notification content using UNMutableNotificationContent let notificationContent = UNMutableNotificationContent() notificationContent.title = "Swift Notification Test" // Notification title notificationContent.subtitle = "macOS Local Notification" // Optional subtitle notificationContent.body = "This is a notification created with UNMutableNotificationContent" // Main content notificationContent.sound = .default // Optional notification sound (set to nil for no sound) notificationContent.badge = 1 // Optional app icon badge (set to nil for no badge) // 3. Set trigger condition (here: "trigger after 3 seconds"; can also use time/calendar triggers) let notificationTrigger = UNTimeIntervalNotificationTrigger( timeInterval: 3, // Delay in seconds repeats: false // Whether to repeat (false = one-time only) ) // 4. Create a notification request (requires a unique ID for later cancellation if needed) let notificationRequest = UNNotificationRequest( identifier: "SwiftMacNotification_001", // Unique identifier content: notificationContent, trigger: notificationTrigger ) // 5. Add the request to the notification center and wait for triggering notificationCenter.add(notificationRequest) { error in if let error = error { print("Notification delivery failed: \(error.localizedDescription)") } else { print("Notification added to queue; will trigger in 3 seconds") } } } } }
0
0
43
6d