|
| 1 | +import AppKit |
1 | 2 | import Foundation |
2 | 3 | import UserNotifications |
3 | 4 |
|
| 5 | +/// Delegate that allows notifications to be displayed even when the app is frontmost. |
| 6 | +final class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate { |
| 7 | + static let shared = NotificationDelegate() |
| 8 | + |
| 9 | + func userNotificationCenter( |
| 10 | + _ center: UNUserNotificationCenter, |
| 11 | + willPresent notification: UNNotification, |
| 12 | + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void |
| 13 | + ) { |
| 14 | + completionHandler([.banner, .sound]) |
| 15 | + } |
| 16 | +} |
| 17 | + |
4 | 18 | @Observable |
5 | 19 | final class ChatState { |
6 | 20 | /// The visible messages — a tail window of allMessages. |
@@ -39,17 +53,30 @@ final class ChatState { |
39 | 53 | } |
40 | 54 |
|
41 | 55 | private func requestNotificationPermission() { |
42 | | - UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, _ in } |
| 56 | + let center = UNUserNotificationCenter.current() |
| 57 | + center.delegate = NotificationDelegate.shared |
| 58 | + center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in |
| 59 | + if let error { |
| 60 | + print("[Notifications] authorization error: \(error)") |
| 61 | + } else if !granted { |
| 62 | + print("[Notifications] user denied notification permission") |
| 63 | + } |
| 64 | + } |
43 | 65 | } |
44 | 66 |
|
45 | 67 | private func postNotification(title: String, body: String) { |
46 | | - guard !isAppFocused else { return } |
| 68 | + // Skip if the app window is currently active |
| 69 | + guard !NSApp.isActive else { return } |
47 | 70 | let content = UNMutableNotificationContent() |
48 | 71 | content.title = title |
49 | 72 | content.body = body |
50 | 73 | content.sound = .default |
51 | 74 | let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil) |
52 | | - UNUserNotificationCenter.current().add(request) |
| 75 | + UNUserNotificationCenter.current().add(request) { error in |
| 76 | + if let error { |
| 77 | + print("[Notifications] delivery error: \(error)") |
| 78 | + } |
| 79 | + } |
53 | 80 | } |
54 | 81 |
|
55 | 82 | func updateBaseURL(_ url: URL) { |
|
0 commit comments