AppDelegate.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. //
  2. // AppDelegate.swift
  3. // LoopFollow
  4. //
  5. // Created by Jon Fawcett on 6/1/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import UIKit
  9. import CoreData
  10. import UserNotifications
  11. import EventKit
  12. @UIApplicationMain
  13. class AppDelegate: UIResponder, UIApplicationDelegate {
  14. var window: UIWindow?
  15. let notificationCenter = UNUserNotificationCenter.current()
  16. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  17. LogManager.shared.log(category: .general, message: "App started")
  18. LogManager.shared.cleanupOldLogs()
  19. let options: UNAuthorizationOptions = [.alert, .sound, .badge]
  20. notificationCenter.requestAuthorization(options: options) {
  21. (didAllow, error) in
  22. if !didAllow {
  23. print("User has declined notifications")
  24. }
  25. }
  26. let store = EKEventStore()
  27. store.requestCalendarAccess { (granted, error) in
  28. if !granted {
  29. print("Failed to get calendar access: \(String(describing: error))")
  30. return
  31. }
  32. }
  33. let action = UNNotificationAction(identifier: "OPEN_APP_ACTION", title: "Open App", options: .foreground)
  34. let category = UNNotificationCategory(identifier: "loopfollow.background.alert", actions: [action], intentIdentifiers: [], options: [])
  35. UNUserNotificationCenter.current().setNotificationCategories([category])
  36. UNUserNotificationCenter.current().delegate = self
  37. // Ensure ViewControllerManager is initialized
  38. _ = ViewControllerManager.shared
  39. _ = BLEManager.shared
  40. return true
  41. }
  42. func applicationWillTerminate(_ application: UIApplication) {
  43. if UserDefaultsRepository.alertAppInactive.value {
  44. AlarmSound.setSoundFile(str: "Alarm_Buzzer")
  45. AlarmSound.playTerminated()
  46. }
  47. }
  48. // MARK: UISceneSession Lifecycle
  49. func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  50. // set "prevent screen lock" to ON when the app is started for the first time
  51. if !UserDefaultsRepository.screenlockSwitchState.exists {
  52. UserDefaultsRepository.screenlockSwitchState.value = true
  53. }
  54. // set the "prevent screen lock" option when the app is started
  55. // This method doesn't seem to be working anymore. Added to view controllers as solution offered on SO
  56. UIApplication.shared.isIdleTimerDisabled = UserDefaultsRepository.screenlockSwitchState.value
  57. return true
  58. }
  59. func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
  60. // Called when a new scene session is being created.
  61. // Use this method to select a configuration to create the new scene with.
  62. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  63. }
  64. func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
  65. // Called when the user discards a scene session.
  66. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  67. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  68. }
  69. // MARK: - Core Data stack
  70. lazy var persistentContainer: NSPersistentCloudKitContainer = {
  71. /*
  72. The persistent container for the application. This implementation
  73. creates and returns a container, having loaded the store for the
  74. application to it. This property is optional since there are legitimate
  75. error conditions that could cause the creation of the store to fail.
  76. */
  77. let container = NSPersistentCloudKitContainer(name: "LoopFollow")
  78. container.loadPersistentStores(completionHandler: { (storeDescription, error) in
  79. if let error = error as NSError? {
  80. // Replace this implementation with code to handle the error appropriately.
  81. // 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.
  82. /*
  83. Typical reasons for an error here include:
  84. * The parent directory does not exist, cannot be created, or disallows writing.
  85. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  86. * The device is out of space.
  87. * The store could not be migrated to the current model version.
  88. Check the error message to determine what the actual problem was.
  89. */
  90. fatalError("Unresolved error \(error), \(error.userInfo)")
  91. }
  92. })
  93. return container
  94. }()
  95. // MARK: - Core Data Saving support
  96. func saveContext () {
  97. let context = persistentContainer.viewContext
  98. if context.hasChanges {
  99. do {
  100. try context.save()
  101. } catch {
  102. // Replace this implementation with code to handle the error appropriately.
  103. // 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.
  104. let nserror = error as NSError
  105. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  106. }
  107. }
  108. }
  109. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  110. if response.actionIdentifier == "OPEN_APP_ACTION" {
  111. if let window = window {
  112. window.rootViewController?.dismiss(animated: true, completion: nil)
  113. window.rootViewController?.present(MainViewController(), animated: true, completion: nil)
  114. }
  115. }
  116. completionHandler()
  117. }
  118. }
  119. extension AppDelegate: UNUserNotificationCenterDelegate {
  120. func userNotificationCenter(_ center: UNUserNotificationCenter,
  121. willPresent notification: UNNotification,
  122. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
  123. {
  124. completionHandler(.alert)
  125. }
  126. }