AppDelegate.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // LoopFollow
  2. // AppDelegate.swift
  3. import CoreData
  4. import EventKit
  5. import UIKit
  6. import UserNotifications
  7. @main
  8. class AppDelegate: UIResponder, UIApplicationDelegate {
  9. var window: UIWindow?
  10. let notificationCenter = UNUserNotificationCenter.current()
  11. func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  12. LogManager.shared.log(category: .general, message: "App started")
  13. LogManager.shared.cleanupOldLogs()
  14. let options: UNAuthorizationOptions = [.alert, .sound, .badge]
  15. notificationCenter.requestAuthorization(options: options) {
  16. didAllow, _ in
  17. if !didAllow {
  18. LogManager.shared.log(category: .general, message: "User has declined notifications")
  19. }
  20. }
  21. let store = EKEventStore()
  22. store.requestCalendarAccess { granted, error in
  23. if !granted {
  24. LogManager.shared.log(category: .calendar, message: "Failed to get calendar access: \(String(describing: error))")
  25. return
  26. }
  27. }
  28. let action = UNNotificationAction(identifier: "OPEN_APP_ACTION", title: "Open App", options: .foreground)
  29. let category = UNNotificationCategory(identifier: BackgroundAlertIdentifier.categoryIdentifier, actions: [action], intentIdentifiers: [], options: [])
  30. UNUserNotificationCenter.current().setNotificationCategories([category])
  31. UNUserNotificationCenter.current().delegate = self
  32. _ = BLEManager.shared
  33. // Ensure VolumeButtonHandler is initialized so it can receive alarm notifications
  34. _ = VolumeButtonHandler.shared
  35. // Register for remote notifications
  36. DispatchQueue.main.async {
  37. UIApplication.shared.registerForRemoteNotifications()
  38. }
  39. BackgroundRefreshManager.shared.register()
  40. // Detect Before-First-Unlock launch. If protected data is unavailable here,
  41. // StorageValues were cached from encrypted UserDefaults and need a reload
  42. // on the first foreground after the user unlocks.
  43. let bfu = !UIApplication.shared.isProtectedDataAvailable
  44. Storage.shared.needsBFUReload = bfu
  45. LogManager.shared.log(category: .general, message: "BFU check: isProtectedDataAvailable=\(!bfu), needsBFUReload=\(bfu)")
  46. return true
  47. }
  48. func applicationWillTerminate(_: UIApplication) {
  49. #if !targetEnvironment(macCatalyst)
  50. LiveActivityManager.shared.endOnTerminate()
  51. #endif
  52. }
  53. // MARK: - Remote Notifications
  54. /// Called when successfully registered for remote notifications
  55. func application(_: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  56. let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  57. Observable.shared.loopFollowDeviceToken.value = tokenString
  58. LogManager.shared.log(category: .apns, message: "Successfully registered for remote notifications with token: \(tokenString)")
  59. }
  60. /// Called when failed to register for remote notifications
  61. func application(_: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  62. LogManager.shared.log(category: .apns, message: "Failed to register for remote notifications: \(error.localizedDescription)")
  63. }
  64. /// Called when a remote notification is received
  65. func application(_: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  66. LogManager.shared.log(category: .apns, message: "Received remote notification: \(userInfo)")
  67. // Check if this is a response notification from Loop or Trio
  68. if let aps = userInfo["aps"] as? [String: Any] {
  69. // Handle visible notification (alert, sound, badge)
  70. if let alert = aps["alert"] as? [String: Any] {
  71. let title = alert["title"] as? String ?? ""
  72. let body = alert["body"] as? String ?? ""
  73. LogManager.shared.log(category: .apns, message: "Notification - Title: \(title), Body: \(body)")
  74. }
  75. // Handle silent notification (content-available)
  76. if let contentAvailable = aps["content-available"] as? Int, contentAvailable == 1 {
  77. // This is a silent push, nothing implemented but logging for now
  78. if let commandStatus = userInfo["command_status"] as? String {
  79. LogManager.shared.log(category: .apns, message: "Command status: \(commandStatus)")
  80. }
  81. if let commandType = userInfo["command_type"] as? String {
  82. LogManager.shared.log(category: .apns, message: "Command type: \(commandType)")
  83. }
  84. }
  85. }
  86. // Call completion handler
  87. completionHandler(.newData)
  88. }
  89. // MARK: - URL handling
  90. // Note: with scene-based lifecycle (iOS 13+), URLs are delivered to
  91. // SceneDelegate.scene(_:openURLContexts:) — not here. The scene delegate
  92. // handles <urlScheme>://la-tap for Live Activity tap navigation.
  93. // MARK: UISceneSession Lifecycle
  94. func application(_: UIApplication, willFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  95. // set the "prevent screen lock" option when the app is started
  96. // This method doesn't seem to be working anymore. Added to view controllers as solution offered on SO
  97. UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
  98. return true
  99. }
  100. func application(_: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options _: UIScene.ConnectionOptions) -> UISceneConfiguration {
  101. // Called when a new scene session is being created.
  102. // Use this method to select a configuration to create the new scene with.
  103. UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  104. }
  105. func application(_: UIApplication, didDiscardSceneSessions _: Set<UISceneSession>) {
  106. // Called when the user discards a scene session.
  107. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  108. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  109. }
  110. // MARK: - Core Data stack
  111. lazy var persistentContainer: NSPersistentCloudKitContainer = {
  112. /*
  113. The persistent container for the application. This implementation
  114. creates and returns a container, having loaded the store for the
  115. application to it. This property is optional since there are legitimate
  116. error conditions that could cause the creation of the store to fail.
  117. */
  118. let container = NSPersistentCloudKitContainer(name: "LoopFollow")
  119. container.loadPersistentStores(completionHandler: { _, error in
  120. if let error = error as NSError? {
  121. // Replace this implementation with code to handle the error appropriately.
  122. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  123. /*
  124. Typical reasons for an error here include:
  125. * The parent directory does not exist, cannot be created, or disallows writing.
  126. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  127. * The device is out of space.
  128. * The store could not be migrated to the current model version.
  129. Check the error message to determine what the actual problem was.
  130. */
  131. fatalError("Unresolved error \(error), \(error.userInfo)")
  132. }
  133. })
  134. return container
  135. }()
  136. // MARK: - Core Data Saving support
  137. func saveContext() {
  138. let context = persistentContainer.viewContext
  139. if context.hasChanges {
  140. do {
  141. try context.save()
  142. } catch {
  143. // Replace this implementation with code to handle the error appropriately.
  144. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  145. let nserror = error as NSError
  146. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  147. }
  148. }
  149. }
  150. func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  151. if response.actionIdentifier == "OPEN_APP_ACTION" {
  152. if let window {
  153. window.rootViewController?.dismiss(animated: true, completion: nil)
  154. window.rootViewController?.present(MainViewController(), animated: true, completion: nil)
  155. }
  156. }
  157. if response.actionIdentifier == "snooze" {
  158. AlarmManager.shared.performSnooze()
  159. }
  160. completionHandler()
  161. }
  162. func application(_: UIApplication, supportedInterfaceOrientationsFor _: UIWindow?) -> UIInterfaceOrientationMask {
  163. let forcePortrait = Storage.shared.forcePortraitMode.value
  164. if forcePortrait {
  165. return .portrait
  166. } else {
  167. return .all
  168. }
  169. }
  170. }
  171. extension AppDelegate: UNUserNotificationCenterDelegate {
  172. func userNotificationCenter(_: UNUserNotificationCenter,
  173. willPresent notification: UNNotification,
  174. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
  175. {
  176. // Log the notification
  177. let userInfo = notification.request.content.userInfo
  178. LogManager.shared.log(category: .general, message: "Will present notification: \(userInfo)")
  179. // Show the notification even when app is in foreground
  180. completionHandler([.banner, .sound, .badge])
  181. }
  182. }