AppDelegate.swift 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // LoopFollow
  2. // AppDelegate.swift
  3. import CoreData
  4. import EventKit
  5. import UIKit
  6. import UserNotifications
  7. @UIApplicationMain
  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: "loopfollow.background.alert", 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. return true
  40. }
  41. func applicationWillTerminate(_: UIApplication) {}
  42. // MARK: - Remote Notifications
  43. // Called when successfully registered for remote notifications
  44. func application(_: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  45. let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
  46. Observable.shared.loopFollowDeviceToken.value = tokenString
  47. LogManager.shared.log(category: .general, message: "Successfully registered for remote notifications with token: \(tokenString)")
  48. }
  49. // Called when failed to register for remote notifications
  50. func application(_: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  51. LogManager.shared.log(category: .general, message: "Failed to register for remote notifications: \(error.localizedDescription)")
  52. }
  53. // Called when a remote notification is received
  54. func application(_: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  55. LogManager.shared.log(category: .general, message: "Received remote notification: \(userInfo)")
  56. // Check if this is a notification from Trio with status update
  57. if let aps = userInfo["aps"] as? [String: Any] {
  58. // Handle visible notification (alert, sound, badge)
  59. if let alert = aps["alert"] as? [String: Any] {
  60. let title = alert["title"] as? String ?? ""
  61. let body = alert["body"] as? String ?? ""
  62. LogManager.shared.log(category: .general, message: "Notification - Title: \(title), Body: \(body)")
  63. }
  64. // Handle silent notification (content-available)
  65. if let contentAvailable = aps["content-available"] as? Int, contentAvailable == 1 {
  66. // This is a silent push, nothing implemented but logging for now
  67. if let commandStatus = userInfo["command_status"] as? String {
  68. LogManager.shared.log(category: .general, message: "Command status: \(commandStatus)")
  69. }
  70. if let commandType = userInfo["command_type"] as? String {
  71. LogManager.shared.log(category: .general, message: "Command type: \(commandType)")
  72. }
  73. }
  74. }
  75. // Call completion handler
  76. completionHandler(.newData)
  77. }
  78. // MARK: UISceneSession Lifecycle
  79. func application(_: UIApplication, willFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  80. // set the "prevent screen lock" option when the app is started
  81. // This method doesn't seem to be working anymore. Added to view controllers as solution offered on SO
  82. UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
  83. return true
  84. }
  85. func application(_: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options _: UIScene.ConnectionOptions) -> UISceneConfiguration {
  86. // Called when a new scene session is being created.
  87. // Use this method to select a configuration to create the new scene with.
  88. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  89. }
  90. func application(_: UIApplication, didDiscardSceneSessions _: Set<UISceneSession>) {
  91. // Called when the user discards a scene session.
  92. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  93. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  94. }
  95. // MARK: - Core Data stack
  96. lazy var persistentContainer: NSPersistentCloudKitContainer = {
  97. /*
  98. The persistent container for the application. This implementation
  99. creates and returns a container, having loaded the store for the
  100. application to it. This property is optional since there are legitimate
  101. error conditions that could cause the creation of the store to fail.
  102. */
  103. let container = NSPersistentCloudKitContainer(name: "LoopFollow")
  104. container.loadPersistentStores(completionHandler: { _, error in
  105. if let error = error as NSError? {
  106. // Replace this implementation with code to handle the error appropriately.
  107. // 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.
  108. /*
  109. Typical reasons for an error here include:
  110. * The parent directory does not exist, cannot be created, or disallows writing.
  111. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  112. * The device is out of space.
  113. * The store could not be migrated to the current model version.
  114. Check the error message to determine what the actual problem was.
  115. */
  116. fatalError("Unresolved error \(error), \(error.userInfo)")
  117. }
  118. })
  119. return container
  120. }()
  121. // MARK: - Core Data Saving support
  122. func saveContext() {
  123. let context = persistentContainer.viewContext
  124. if context.hasChanges {
  125. do {
  126. try context.save()
  127. } catch {
  128. // Replace this implementation with code to handle the error appropriately.
  129. // 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.
  130. let nserror = error as NSError
  131. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  132. }
  133. }
  134. }
  135. func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  136. if response.actionIdentifier == "OPEN_APP_ACTION" {
  137. if let window = window {
  138. window.rootViewController?.dismiss(animated: true, completion: nil)
  139. window.rootViewController?.present(MainViewController(), animated: true, completion: nil)
  140. }
  141. }
  142. if response.actionIdentifier == "snooze" {
  143. AlarmManager.shared.performSnooze()
  144. }
  145. completionHandler()
  146. }
  147. func application(_: UIApplication, supportedInterfaceOrientationsFor _: UIWindow?) -> UIInterfaceOrientationMask {
  148. let forcePortrait = Storage.shared.forcePortraitMode.value
  149. if forcePortrait {
  150. return .portrait
  151. } else {
  152. return .all
  153. }
  154. }
  155. }
  156. extension AppDelegate: UNUserNotificationCenterDelegate {
  157. func userNotificationCenter(_: UNUserNotificationCenter,
  158. willPresent notification: UNNotification,
  159. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
  160. {
  161. // Log the notification
  162. let userInfo = notification.request.content.userInfo
  163. LogManager.shared.log(category: .general, message: "Will present notification: \(userInfo)")
  164. // Show the notification even when app is in foreground
  165. completionHandler([.banner, .sound, .badge])
  166. }
  167. }