AppDelegate.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // Copyright (C) 2016 Inigo Valentin
  2. //
  3. // This file is part of the Gasteizko Margolariak IOS app.
  4. //
  5. // The Gasteizko Margolariak IOS app is free software: you can
  6. // redistribute it and/or modify it under the terms of the
  7. // GNU General Public License as published by the Free Software
  8. // Foundation, either version 3 of the License, or (at your
  9. // option) any later version.
  10. //
  11. // The Gasteizko Margolariak IOS app is distributed in the
  12. // hope that it will be useful, but WITHOUT ANY WARRANTY;
  13. // without even the implied warranty of MERCHANTABILITY or
  14. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  15. // Public License for more details.
  16. //
  17. // You should have received a copy of the GNU General Public
  18. // License along with the Gasteizko Margolariak IOS app.
  19. // If not, see <http://www.gnu.org/licenses/>.
  20. import UIKit
  21. import CoreData
  22. import GoogleMaps
  23. import UserNotifications
  24. /**
  25. Application delegate.
  26. */
  27. @UIApplicationMain
  28. class AppDelegate: UIResponder, UIApplicationDelegate {
  29. var window: UIWindow?
  30. var controller: ViewController?
  31. var albumController: AlbumViewController?
  32. var syncController: SyncController?
  33. var scheduleController: ScheduleViewController?
  34. var futureActivityController: FutureActivityViewController?
  35. /**
  36. Application opened normally. Request permissions amd defines some settings.
  37. */
  38. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  39. // Google Mapas API KEY
  40. GMSServices.provideAPIKey("AIzaSyBfIiBM_YSBlxybmI_Uz_fGoUFN4wacR80")
  41. // Enable background mode.
  42. UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
  43. // Enable notifications (for iOS 10)
  44. if #available(iOS 10.0, *) {
  45. let center = UNUserNotificationCenter.current()
  46. center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
  47. // Notification authorization granted
  48. }
  49. } else {
  50. // No notifications for iOS < 10
  51. }
  52. return true
  53. }
  54. /**
  55. Application run in the background. Fectches notifications and syncs with the server.
  56. */
  57. func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  58. NSLog(":BACKGROUND:LOG: Start bg sync...")
  59. Notifications()
  60. Sync()
  61. let when = DispatchTime.now() + 180 // 3 minutes to perform the sync.
  62. DispatchQueue.main.asyncAfter(deadline: when) {
  63. completionHandler(UIBackgroundFetchResult.newData)
  64. }
  65. }
  66. /**
  67. Sent when the application is about to move from active to inactive state.
  68. This can occur for certain types of temporary interruptions
  69. (such as an incoming phone call or SMS message) or when the user quits
  70. the application and it begins the transition to the background state.
  71. Use this method to pause ongoing tasks, disable timers, and invalidate
  72. graphics rendering callbacks. Games should use this method to pause the game.
  73. */
  74. func applicationWillResignActive(_ application: UIApplication) {
  75. }
  76. /**
  77. Use this method to release shared resources, save user data, invalidate
  78. timers, and store enough application state information to restore your
  79. application to its current state in case it is terminated later.
  80. If your application supports background execution, this method is called
  81. instead of applicationWillTerminate: when the user quits.
  82. */
  83. func applicationDidEnterBackground(_ application: UIApplication) {
  84. }
  85. /**
  86. Called as part of the transition from the background to the active state;
  87. here you can undo many of the changes made on entering the background.
  88. */
  89. func applicationWillEnterForeground(_ application: UIApplication) {
  90. }
  91. /**
  92. Restart any tasks that were paused (or not yet started) while the
  93. application was inactive. If the application was previously in the background,
  94. optionally refresh the user interface.
  95. */
  96. func applicationDidBecomeActive(_ application: UIApplication) {
  97. }
  98. /**
  99. Called when the application is about to terminate. Save data if appropriate.
  100. See also applicationDidEnterBackground:.
  101. Saves changes in the application's managed object context before the application terminates.
  102. */
  103. func applicationWillTerminate(_ application: UIApplication) {
  104. }
  105. // MARK: - Core Data stack
  106. // The directory the application uses to store the Core Data store file.
  107. lazy var applicationDocumentsDirectory: URL = {
  108. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
  109. return urls[urls.count-1]
  110. }()
  111. // The managed object model for the application
  112. lazy var managedObjectModel: NSManagedObjectModel = {
  113. let modelURL = Bundle.main.url(forResource: "app", withExtension: "momd")!
  114. return NSManagedObjectModel(contentsOf: modelURL)!
  115. }()
  116. // he persistent store coordinator for the application
  117. lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
  118. let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
  119. let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
  120. var failureReason = "There was an error creating or loading the application's saved data."
  121. do {
  122. try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
  123. } catch {
  124. // Report any error we got.
  125. var dict = [String: AnyObject]()
  126. dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
  127. dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
  128. dict[NSUnderlyingErrorKey] = error as NSError
  129. let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
  130. NSLog(":DELEGATE:ERROR: Unresolved error \(wrappedError), \(wrappedError.userInfo)")
  131. abort()
  132. }
  133. return coordinator
  134. }()
  135. // Returns the managed object context for the application
  136. lazy var managedObjectContext: NSManagedObjectContext = {
  137. let coordinator = self.persistentStoreCoordinator
  138. var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
  139. managedObjectContext.persistentStoreCoordinator = coordinator
  140. return managedObjectContext
  141. }()
  142. // MARK: - Core Data Saving support
  143. /**
  144. Saves the application context.
  145. */
  146. func saveContext () {
  147. if managedObjectContext.hasChanges {
  148. do {
  149. try managedObjectContext.save()
  150. } catch {
  151. // Replace this implementation with code to handle the error appropriately.
  152. // abort() 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.
  153. let nserror = error as NSError
  154. NSLog(":DELEGATE:ERROR: Unresolved error \(nserror), \(nserror.userInfo)")
  155. abort()
  156. }
  157. }
  158. }
  159. }