AppDelegate.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. do {
  23. try await TrioRemoteControl.shared.handleRemoteNotification(pushMessage: pushMessage)
  24. completionHandler(.newData)
  25. } catch {
  26. debug(
  27. .default,
  28. "\(DebuggingIdentifiers.failed) failed to handle remote notification with error: \(error.localizedDescription)"
  29. )
  30. }
  31. }
  32. } catch {
  33. debug(.remoteControl, "Error decoding push message: \(error.localizedDescription)")
  34. completionHandler(.failed)
  35. }
  36. }
  37. func application(
  38. _: UIApplication,
  39. didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
  40. ) {
  41. let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
  42. let token = tokenParts.joined()
  43. Task {
  44. do {
  45. try await TrioRemoteControl.shared.handleAPNSChanges(deviceToken: token)
  46. } catch {
  47. debug(
  48. .remoteControl,
  49. "\(DebuggingIdentifiers.failed) failed to register for remote notifications: \(error.localizedDescription)"
  50. )
  51. }
  52. }
  53. }
  54. func application(
  55. _: UIApplication,
  56. didFailToRegisterForRemoteNotificationsWithError error: Error
  57. ) {
  58. debug(.remoteControl, "Failed to register for remote notifications: \(error.localizedDescription)")
  59. }
  60. }