AppDelegate.swift 9.2 KB

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