WatchNotificationHandler.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import Foundation
  2. import UserNotifications
  3. import WatchConnectivity
  4. final class WatchNotificationHandler: NSObject, UNUserNotificationCenterDelegate {
  5. static let shared = WatchNotificationHandler()
  6. override private init() {
  7. super.init()
  8. }
  9. func configure() {
  10. let center = UNUserNotificationCenter.current()
  11. center.delegate = self
  12. registerCategories(on: center)
  13. }
  14. private func registerCategories(on center: UNUserNotificationCenter) {
  15. center.getNotificationCategories { existingCategories in
  16. let glucoseCategory = NotificationCategoryFactory.createGlucoseCategory()
  17. var categories = existingCategories
  18. categories.update(with: glucoseCategory)
  19. // UNUserNotificationCenter methods should be called on main thread
  20. Task { @MainActor in
  21. center.setNotificationCategories(categories)
  22. }
  23. }
  24. }
  25. /// UNUserNotificationCenterDelegate method called when user interacts with a notification on watch.
  26. /// This can be called off the main thread. WCSession.transferUserInfo is thread-safe.
  27. func userNotificationCenter(
  28. _: UNUserNotificationCenter,
  29. didReceive response: UNNotificationResponse,
  30. withCompletionHandler completionHandler: @escaping () -> Void
  31. ) {
  32. defer { completionHandler() }
  33. guard let action = NotificationResponseAction(rawValue: response.actionIdentifier) else { return }
  34. sendSnoozeRequest(for: action)
  35. }
  36. /// Sends snooze request to iPhone via WatchConnectivity.
  37. /// WCSession.transferUserInfo is thread-safe and can be called from any thread.
  38. private func sendSnoozeRequest(for action: NotificationResponseAction) {
  39. guard WCSession.isSupported() else { return }
  40. let payload: [String: Any] = [WatchMessageKeys.snoozeDuration: action.minutes]
  41. WCSession.default.transferUserInfo(payload)
  42. }
  43. }