AppDelegate.swift 6.8 KB

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