AppDelegate.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. // Telemetry: record this cold launch (used by the rolling
  41. // coldLaunches7d signal). If the running build's SHA differs from
  42. // the one we last sent for, fire an immediate ping — the scheduler
  43. // alone can't notice an app update. Otherwise let the 24h scheduler
  44. // handle cadence: its first run is lastSentAt + 24h, so a relaunch
  45. // a few hours after the previous send simply waits out the
  46. // remainder. See Helpers/Telemetry.swift.
  47. TelemetryClient.shared.recordColdLaunch()
  48. Task.detached {
  49. if TelemetryClient.shared.buildShaChangedSinceLastSend() {
  50. await TelemetryClient.shared.maybeSend()
  51. }
  52. TelemetryClient.shared.scheduleRecurring()
  53. }
  54. // Detect Before-First-Unlock launch. If protected data is unavailable here,
  55. // StorageValues were cached from encrypted UserDefaults and need a reload
  56. // on the first foreground after the user unlocks.
  57. let bfu = !UIApplication.shared.isProtectedDataAvailable
  58. Storage.shared.needsBFUReload = bfu
  59. LogManager.shared.log(category: .general, message: "BFU check: isProtectedDataAvailable=\(!bfu), needsBFUReload=\(bfu)")
  60. return true
  61. }
  62. func applicationWillTerminate(_: UIApplication) {
  63. #if !targetEnvironment(macCatalyst)
  64. LiveActivityManager.shared.endOnTerminate()
  65. #endif
  66. }
  67. // MARK: - Remote Notifications
  68. /// Called when successfully registered for remote notifications
  69. func application(_: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  70. let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  71. Observable.shared.loopFollowDeviceToken.value = tokenString
  72. LogManager.shared.log(category: .apns, message: "Successfully registered for remote notifications with token: \(LogRedactor.tail(tokenString))")
  73. }
  74. /// Called when failed to register for remote notifications
  75. func application(_: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  76. LogManager.shared.log(category: .apns, message: "Failed to register for remote notifications: \(error.localizedDescription)")
  77. }
  78. /// Called when a remote notification is received
  79. func application(_: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  80. let userInfoKeys = userInfo.keys.compactMap { $0 as? String }.sorted()
  81. LogManager.shared.log(category: .apns, message: "Received remote notification: keys=\(userInfoKeys)")
  82. // Check if this is a response notification from Loop or Trio
  83. if let aps = userInfo["aps"] as? [String: Any] {
  84. // Handle visible notification (alert, sound, badge)
  85. if let alert = aps["alert"] as? [String: Any] {
  86. let title = alert["title"] as? String ?? ""
  87. let body = alert["body"] as? String ?? ""
  88. LogManager.shared.log(category: .apns, message: "Notification - Title: \(title), Body: \(body)")
  89. }
  90. // Handle silent notification (content-available)
  91. if let contentAvailable = aps["content-available"] as? Int, contentAvailable == 1 {
  92. // This is a silent push, nothing implemented but logging for now
  93. if let commandStatus = userInfo["command_status"] as? String {
  94. LogManager.shared.log(category: .apns, message: "Command status: \(commandStatus)")
  95. }
  96. if let commandType = userInfo["command_type"] as? String {
  97. LogManager.shared.log(category: .apns, message: "Command type: \(commandType)")
  98. }
  99. }
  100. }
  101. // Call completion handler
  102. completionHandler(.newData)
  103. }
  104. // MARK: - URL handling
  105. // Note: with scene-based lifecycle (iOS 13+), URLs are delivered to
  106. // SceneDelegate.scene(_:openURLContexts:) — not here. The scene delegate
  107. // handles <urlScheme>://la-tap for Live Activity tap navigation.
  108. // MARK: UISceneSession Lifecycle
  109. func application(_: UIApplication, willFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  110. // set the "prevent screen lock" option when the app is started
  111. // This method doesn't seem to be working anymore. Added to view controllers as solution offered on SO
  112. UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
  113. return true
  114. }
  115. func application(_: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options _: UIScene.ConnectionOptions) -> UISceneConfiguration {
  116. // Called when a new scene session is being created.
  117. // Use this method to select a configuration to create the new scene with.
  118. UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  119. }
  120. func application(_: UIApplication, didDiscardSceneSessions _: Set<UISceneSession>) {
  121. // Called when the user discards a scene session.
  122. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  123. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  124. }
  125. // MARK: - Core Data stack
  126. lazy var persistentContainer: NSPersistentCloudKitContainer = {
  127. /*
  128. The persistent container for the application. This implementation
  129. creates and returns a container, having loaded the store for the
  130. application to it. This property is optional since there are legitimate
  131. error conditions that could cause the creation of the store to fail.
  132. */
  133. let container = NSPersistentCloudKitContainer(name: "LoopFollow")
  134. container.loadPersistentStores(completionHandler: { _, error in
  135. if let error = error as NSError? {
  136. // Replace this implementation with code to handle the error appropriately.
  137. // 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.
  138. /*
  139. Typical reasons for an error here include:
  140. * The parent directory does not exist, cannot be created, or disallows writing.
  141. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  142. * The device is out of space.
  143. * The store could not be migrated to the current model version.
  144. Check the error message to determine what the actual problem was.
  145. */
  146. fatalError("Unresolved error \(error), \(error.userInfo)")
  147. }
  148. })
  149. return container
  150. }()
  151. // MARK: - Core Data Saving support
  152. func saveContext() {
  153. let context = persistentContainer.viewContext
  154. if context.hasChanges {
  155. do {
  156. try context.save()
  157. } catch {
  158. // Replace this implementation with code to handle the error appropriately.
  159. // 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.
  160. let nserror = error as NSError
  161. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  162. }
  163. }
  164. }
  165. func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  166. if response.actionIdentifier == "OPEN_APP_ACTION" {
  167. if let window {
  168. window.rootViewController?.dismiss(animated: true, completion: nil)
  169. window.rootViewController?.present(MainViewController(), animated: true, completion: nil)
  170. }
  171. }
  172. if response.actionIdentifier == "snooze" {
  173. AlarmManager.shared.performSnooze()
  174. }
  175. completionHandler()
  176. }
  177. func application(_: UIApplication, supportedInterfaceOrientationsFor _: UIWindow?) -> UIInterfaceOrientationMask {
  178. let forcePortrait = Storage.shared.forcePortraitMode.value
  179. if forcePortrait {
  180. return .portrait
  181. } else {
  182. return .all
  183. }
  184. }
  185. }
  186. extension AppDelegate: UNUserNotificationCenterDelegate {
  187. func userNotificationCenter(_: UNUserNotificationCenter,
  188. willPresent notification: UNNotification,
  189. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
  190. {
  191. // Log the notification
  192. let userInfo = notification.request.content.userInfo
  193. let userInfoKeys = userInfo.keys.compactMap { $0 as? String }.sorted()
  194. LogManager.shared.log(category: .general, message: "Will present notification: keys=\(userInfoKeys)")
  195. // Show the notification even when app is in foreground
  196. completionHandler([.banner, .sound, .badge])
  197. }
  198. }