AppDelegate.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import SwiftUI
  2. import UIKit
  3. import UserNotifications
  4. class AppDelegate: NSObject, UIApplicationDelegate, ObservableObject, UNUserNotificationCenterDelegate {
  5. func application(
  6. _ application: UIApplication,
  7. didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?
  8. ) -> Bool {
  9. UNUserNotificationCenter.current().delegate = self
  10. application.registerForRemoteNotifications()
  11. return true
  12. }
  13. func application(
  14. _: UIApplication,
  15. didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  16. fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
  17. ) {
  18. debug(.remoteControl, "Received notification")
  19. do {
  20. let jsonData = try JSONSerialization.data(withJSONObject: userInfo)
  21. let pushMessage = try JSONDecoder().decode(PushMessage.self, from: jsonData)
  22. Task {
  23. await TrioRemoteControl.shared.handleRemoteNotification(pushMessage: pushMessage)
  24. completionHandler(.newData)
  25. }
  26. } catch {
  27. debug(.remoteControl, "Error decoding push message: \(error.localizedDescription)")
  28. completionHandler(.failed)
  29. }
  30. }
  31. func application(
  32. _: UIApplication,
  33. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
  34. ) {
  35. let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
  36. let token = tokenParts.joined()
  37. Task {
  38. await TrioRemoteControl.shared.handleAPNSChanges(deviceToken: token)
  39. }
  40. }
  41. func application(
  42. _: UIApplication,
  43. didFailToRegisterForRemoteNotificationsWithError error: Error
  44. ) {
  45. debug(.remoteControl, "Failed to register for remote notifications: \(error.localizedDescription)")
  46. }
  47. }