AppDelegate.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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: \(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. LogManager.shared.log(category: .apns, message: "Received remote notification: \(userInfo)")
  81. // Check if this is a response notification from Loop or Trio
  82. if let aps = userInfo["aps"] as? [String: Any] {
  83. // Handle visible notification (alert, sound, badge)
  84. if let alert = aps["alert"] as? [String: Any] {
  85. let title = alert["title"] as? String ?? ""
  86. let body = alert["body"] as? String ?? ""
  87. LogManager.shared.log(category: .apns, message: "Notification - Title: \(title), Body: \(body)")
  88. }
  89. // Handle silent notification (content-available)
  90. if let contentAvailable = aps["content-available"] as? Int, contentAvailable == 1 {
  91. // This is a silent push, nothing implemented but logging for now
  92. if let commandStatus = userInfo["command_status"] as? String {
  93. LogManager.shared.log(category: .apns, message: "Command status: \(commandStatus)")
  94. }
  95. if let commandType = userInfo["command_type"] as? String {
  96. LogManager.shared.log(category: .apns, message: "Command type: \(commandType)")
  97. }
  98. }
  99. }
  100. // Call completion handler
  101. completionHandler(.newData)
  102. }
  103. // MARK: - URL handling
  104. // Note: with scene-based lifecycle (iOS 13+), URLs are delivered to
  105. // SceneDelegate.scene(_:openURLContexts:) — not here. The scene delegate
  106. // handles <urlScheme>://la-tap for Live Activity tap navigation.
  107. // MARK: UISceneSession Lifecycle
  108. func application(_: UIApplication, willFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  109. // set the "prevent screen lock" option when the app is started
  110. // This method doesn't seem to be working anymore. Added to view controllers as solution offered on SO
  111. UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
  112. return true
  113. }
  114. func application(_: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options _: UIScene.ConnectionOptions) -> UISceneConfiguration {
  115. // Called when a new scene session is being created.
  116. // Use this method to select a configuration to create the new scene with.
  117. UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  118. }
  119. func application(_: UIApplication, didDiscardSceneSessions _: Set<UISceneSession>) {
  120. // Called when the user discards a scene session.
  121. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  122. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  123. }
  124. // MARK: - Core Data stack
  125. lazy var persistentContainer: NSPersistentCloudKitContainer = {
  126. /*
  127. The persistent container for the application. This implementation
  128. creates and returns a container, having loaded the store for the
  129. application to it. This property is optional since there are legitimate
  130. error conditions that could cause the creation of the store to fail.
  131. */
  132. let container = NSPersistentCloudKitContainer(name: "LoopFollow")
  133. container.loadPersistentStores(completionHandler: { _, error in
  134. if let error = error as NSError? {
  135. // Replace this implementation with code to handle the error appropriately.
  136. // 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.
  137. /*
  138. Typical reasons for an error here include:
  139. * The parent directory does not exist, cannot be created, or disallows writing.
  140. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  141. * The device is out of space.
  142. * The store could not be migrated to the current model version.
  143. Check the error message to determine what the actual problem was.
  144. */
  145. fatalError("Unresolved error \(error), \(error.userInfo)")
  146. }
  147. })
  148. return container
  149. }()
  150. // MARK: - Core Data Saving support
  151. func saveContext() {
  152. let context = persistentContainer.viewContext
  153. if context.hasChanges {
  154. do {
  155. try context.save()
  156. } catch {
  157. // Replace this implementation with code to handle the error appropriately.
  158. // 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.
  159. let nserror = error as NSError
  160. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  161. }
  162. }
  163. }
  164. func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  165. if response.actionIdentifier == "OPEN_APP_ACTION" {
  166. if let window {
  167. window.rootViewController?.dismiss(animated: true, completion: nil)
  168. window.rootViewController?.present(MainViewController(), animated: true, completion: nil)
  169. }
  170. }
  171. if response.actionIdentifier == "snooze" {
  172. AlarmManager.shared.performSnooze()
  173. }
  174. completionHandler()
  175. }
  176. func application(_: UIApplication, supportedInterfaceOrientationsFor _: UIWindow?) -> UIInterfaceOrientationMask {
  177. let forcePortrait = Storage.shared.forcePortraitMode.value
  178. if forcePortrait {
  179. return .portrait
  180. } else {
  181. return .all
  182. }
  183. }
  184. }
  185. extension AppDelegate: UNUserNotificationCenterDelegate {
  186. func userNotificationCenter(_: UNUserNotificationCenter,
  187. willPresent notification: UNNotification,
  188. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
  189. {
  190. // Log the notification
  191. let userInfo = notification.request.content.userInfo
  192. LogManager.shared.log(category: .general, message: "Will present notification: \(userInfo)")
  193. // Show the notification even when app is in foreground
  194. completionHandler([.banner, .sound, .badge])
  195. }
  196. }