AppDelegate.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. return true
  34. }
  35. func applicationWillTerminate(_: UIApplication) {}
  36. // MARK: UISceneSession Lifecycle
  37. func application(_: UIApplication, willFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  38. // set the "prevent screen lock" option when the app is started
  39. // This method doesn't seem to be working anymore. Added to view controllers as solution offered on SO
  40. UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
  41. return true
  42. }
  43. func application(_: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options _: UIScene.ConnectionOptions) -> UISceneConfiguration {
  44. // Called when a new scene session is being created.
  45. // Use this method to select a configuration to create the new scene with.
  46. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  47. }
  48. func application(_: UIApplication, didDiscardSceneSessions _: Set<UISceneSession>) {
  49. // Called when the user discards a scene session.
  50. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  51. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  52. }
  53. // MARK: - Core Data stack
  54. lazy var persistentContainer: NSPersistentCloudKitContainer = {
  55. /*
  56. The persistent container for the application. This implementation
  57. creates and returns a container, having loaded the store for the
  58. application to it. This property is optional since there are legitimate
  59. error conditions that could cause the creation of the store to fail.
  60. */
  61. let container = NSPersistentCloudKitContainer(name: "LoopFollow")
  62. container.loadPersistentStores(completionHandler: { _, error in
  63. if let error = error as NSError? {
  64. // Replace this implementation with code to handle the error appropriately.
  65. // 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.
  66. /*
  67. Typical reasons for an error here include:
  68. * The parent directory does not exist, cannot be created, or disallows writing.
  69. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  70. * The device is out of space.
  71. * The store could not be migrated to the current model version.
  72. Check the error message to determine what the actual problem was.
  73. */
  74. fatalError("Unresolved error \(error), \(error.userInfo)")
  75. }
  76. })
  77. return container
  78. }()
  79. // MARK: - Core Data Saving support
  80. func saveContext() {
  81. let context = persistentContainer.viewContext
  82. if context.hasChanges {
  83. do {
  84. try context.save()
  85. } catch {
  86. // Replace this implementation with code to handle the error appropriately.
  87. // 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.
  88. let nserror = error as NSError
  89. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  90. }
  91. }
  92. }
  93. func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  94. if response.actionIdentifier == "OPEN_APP_ACTION" {
  95. if let window = window {
  96. window.rootViewController?.dismiss(animated: true, completion: nil)
  97. window.rootViewController?.present(MainViewController(), animated: true, completion: nil)
  98. }
  99. }
  100. if response.actionIdentifier == "snooze" {
  101. AlarmManager.shared.performSnooze()
  102. }
  103. completionHandler()
  104. }
  105. func application(_: UIApplication, supportedInterfaceOrientationsFor _: UIWindow?) -> UIInterfaceOrientationMask {
  106. let forcePortrait = Storage.shared.forcePortraitMode.value
  107. if forcePortrait {
  108. return .portrait
  109. } else {
  110. return .all
  111. }
  112. }
  113. }
  114. extension AppDelegate: UNUserNotificationCenterDelegate {
  115. func userNotificationCenter(_: UNUserNotificationCenter,
  116. willPresent _: UNNotification,
  117. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
  118. {
  119. completionHandler(.alert)
  120. }
  121. }