File size: 1,587 Bytes
2d8be8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

import Foundation
import UserNotifications

@objc public protocol NotificationHandlerProtocol {
  func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions
  func didReceive(response: UNNotificationResponse)
}

@objc public class NotificationManager: NSObject, UNUserNotificationCenterDelegate {
  public weak var notificationHandler: NotificationHandlerProtocol?

  override init() {
    super.init()
    let center = UNUserNotificationCenter.current()
    center.delegate = self
  }

  public func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  ) {
    var presentationOptions: UNNotificationPresentationOptions? = nil

    if notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) != true {
      presentationOptions = notificationHandler?.willPresent(notification: notification)
    }

    completionHandler(presentationOptions ?? [])
  }

  public func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
  ) {
    if response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) != true {
      notificationHandler?.didReceive(response: response)
    }

    completionHandler()
  }
}