11import UserNotifications
22
3- class NotifDelegate : NSObject , UNUserNotificationCenterDelegate {
4- override init ( ) {
5- super. init ( )
3+ extension AppDelegate : UNUserNotificationCenterDelegate {
4+ static func registerNotificationCategories( ) {
5+ let vpnFailure = UNNotificationCategory (
6+ identifier: NotificationCategory . vpnFailure. rawValue,
7+ actions: [ ] ,
8+ intentIdentifiers: [ ] ,
9+ options: [ ]
10+ )
11+
12+ let uriFailure = UNNotificationCategory (
13+ identifier: NotificationCategory . uriFailure. rawValue,
14+ actions: [ ] ,
15+ intentIdentifiers: [ ] ,
16+ options: [ ]
17+ )
18+
19+ UNUserNotificationCenter . current ( )
20+ . setNotificationCategories ( [ vpnFailure, uriFailure] )
621 }
722
823 // This function is required for notifications to appear as banners whilst the app is running.
@@ -13,9 +28,28 @@ class NotifDelegate: NSObject, UNUserNotificationCenterDelegate {
1328 ) async -> UNNotificationPresentationOptions {
1429 [ . banner]
1530 }
31+
32+ nonisolated func userNotificationCenter(
33+ _: UNUserNotificationCenter ,
34+ didReceive response: UNNotificationResponse ,
35+ withCompletionHandler completionHandler: @escaping ( ) -> Void
36+ ) {
37+ let category = response. notification. request. content. categoryIdentifier
38+ let action = response. actionIdentifier
39+ switch ( category, action) {
40+ // Default action for VPN failure notification
41+ case ( NotificationCategory . vpnFailure. rawValue, UNNotificationDefaultActionIdentifier) :
42+ Task { @MainActor in
43+ self . menuBar? . menuBarExtra. toggleVisibility ( )
44+ }
45+ default :
46+ break
47+ }
48+ completionHandler ( )
49+ }
1650}
1751
18- func sendNotification( title: String , body: String ) async throws {
52+ func sendNotification( title: String , body: String , category : NotificationCategory ) async throws {
1953 let nc = UNUserNotificationCenter . current ( )
2054 let granted = try await nc. requestAuthorization ( options: [ . alert, . badge] )
2155 guard granted else {
@@ -24,5 +58,11 @@ func sendNotification(title: String, body: String) async throws {
2458 let content = UNMutableNotificationContent ( )
2559 content. title = title
2660 content. body = body
61+ content. categoryIdentifier = category. rawValue
2762 try await nc. add ( . init( identifier: UUID ( ) . uuidString, content: content, trigger: nil ) )
2863}
64+
65+ enum NotificationCategory : String {
66+ case vpnFailure = " VPN_FAILURE "
67+ case uriFailure = " URI_FAILURE "
68+ }
0 commit comments