AppDelegate.swift 6.5 KB

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