AppDelegate.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. application.registerForRemoteNotifications()
  10. return true
  11. }
  12. func application(
  13. _: UIApplication,
  14. didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  15. fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
  16. ) {
  17. debug(.remoteControl, "Received notification")
  18. do {
  19. let jsonData = try JSONSerialization.data(withJSONObject: userInfo)
  20. let pushMessage = try JSONDecoder().decode(PushMessage.self, from: jsonData)
  21. Task {
  22. await TrioRemoteControl.shared.handleRemoteNotification(pushMessage: pushMessage)
  23. completionHandler(.newData)
  24. }
  25. } catch {
  26. debug(.remoteControl, "Error decoding push message: \(error.localizedDescription)")
  27. completionHandler(.failed)
  28. }
  29. }
  30. func application(
  31. _: UIApplication,
  32. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
  33. ) {
  34. let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
  35. let token = tokenParts.joined()
  36. Task {
  37. await TrioRemoteControl.shared.handleAPNSChanges(deviceToken: token)
  38. }
  39. }
  40. func application(
  41. _: UIApplication,
  42. didFailToRegisterForRemoteNotificationsWithError error: Error
  43. ) {
  44. debug(.remoteControl, "Failed to register for remote notifications: \(error.localizedDescription)")
  45. }
  46. }