AppDelegate.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. //
  2. // AppDelegate.swift
  3. // Gasteizko Margolariak
  4. //
  5. // Created by Inigo Valentin on 2016-08-23
  6. // Copyright © 2016 Inigo Valentin. All rights reserved.
  7. //
  8. // Based on the work of Yuji Hato.
  9. //
  10. import UIKit
  11. import CoreData
  12. @UIApplicationMain
  13. class AppDelegate: UIResponder, UIApplicationDelegate {
  14. var window: UIWindow?
  15. private func createMenuView() {
  16. // create viewController code...
  17. let storyboard = UIStoryboard(name: "Main", bundle: nil)
  18. let mainViewController = storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController
  19. let leftViewController = storyboard.instantiateViewControllerWithIdentifier("LeftViewController") as! LeftViewController
  20. let nvc: UINavigationController = UINavigationController(rootViewController: mainViewController)
  21. UINavigationBar.appearance().tintColor = UIColor.blackColor()
  22. UINavigationBar.appearance().backgroundColor = UIColor(hex: "4c9ed8")
  23. leftViewController.mainViewController = nvc
  24. let slideMenuController = ExSlideMenuController(mainViewController:nvc, leftMenuViewController: leftViewController)
  25. slideMenuController.automaticallyAdjustsScrollViewInsets = true
  26. slideMenuController.delegate = mainViewController
  27. //self.window?.backgroundColor = UIColor(red: 236.0, green: 238.0, blue: 241.0, alpha: 1.0)
  28. self.window?.backgroundColor = UIColor(hex: "c6e4f6")
  29. self.window?.rootViewController = slideMenuController
  30. self.window?.makeKeyAndVisible()
  31. }
  32. func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  33. self.createMenuView()
  34. //Get db version
  35. //NSUserDefaults.standardUserDefaults().setObject("mynameisben", forKey: "username")
  36. if let dbVersion = NSUserDefaults.standardUserDefaults().stringForKey("dbversion"){
  37. print("DB Version: \(dbVersion)")
  38. }
  39. else{
  40. print("DB Verion not set. Fetching content")
  41. //Async task to do the initial sync
  42. let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
  43. dispatch_async(dispatch_get_global_queue(priority, 0)) {
  44. // do some task
  45. let urlPath: String = "http://margolariak.com/app/sync.php"
  46. let url: NSURL = NSURL(string: urlPath)!
  47. let request1: NSURLRequest = NSURLRequest(URL: url)
  48. let queue:NSOperationQueue = NSOperationQueue()
  49. NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
  50. do {
  51. let content = try String(contentsOfURL: url)
  52. //print("HTML : \(content)")
  53. //let newVersion = content.substringWithRange(Range<String.Index>(start: content.rangeOfString("<version>"), end: content.rangeOfString("</version>")))
  54. if let startRange = content.rangeOfString("<version>"), endRange = content.rangeOfString("</version>") {
  55. let newVersion = content[startRange.endIndex..<endRange.startIndex]
  56. print("Remote db Verion : \(newVersion)")
  57. }
  58. } catch let error as NSError {
  59. print(error.localizedDescription)
  60. }
  61. })
  62. dispatch_async(dispatch_get_main_queue()) {
  63. // update some UI
  64. }
  65. }
  66. }
  67. return true
  68. }
  69. func applicationDidFinishLaunching(application: UIApplication) {
  70. print("App launched")
  71. }
  72. func applicationWillResignActive(application: UIApplication) {
  73. // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  74. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
  75. }
  76. func applicationDidEnterBackground(application: UIApplication) {
  77. // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
  78. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  79. }
  80. func applicationWillEnterForeground(application: UIApplication) {
  81. // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
  82. }
  83. func applicationDidBecomeActive(application: UIApplication) {
  84. // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  85. }
  86. func applicationWillTerminate(application: UIApplication) {
  87. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  88. // Saves changes in the application's managed object context before the application terminates.
  89. self.saveContext()
  90. }
  91. // MARK: - Core Data stack
  92. lazy var applicationDocumentsDirectory: NSURL = {
  93. // The directory the application uses to store the Core Data store file. This code uses a directory named "dekatotoro.test11" in the application's documents Application Support directory.
  94. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
  95. return urls[urls.count-1]
  96. }()
  97. lazy var managedObjectModel: NSManagedObjectModel = {
  98. // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
  99. let modelURL = NSBundle.mainBundle().URLForResource("test11", withExtension: "momd")!
  100. return NSManagedObjectModel(contentsOfURL: modelURL)!
  101. }()
  102. lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
  103. // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
  104. // Create the coordinator and store
  105. var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
  106. let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("test11.sqlite")
  107. var error: NSError? = nil
  108. var failureReason = "There was an error creating or loading the application's saved data."
  109. do {
  110. try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
  111. } catch var error1 as NSError {
  112. error = error1
  113. coordinator = nil
  114. // Report any error we got.
  115. var dict = [String: AnyObject]()
  116. dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
  117. dict[NSLocalizedFailureReasonErrorKey] = failureReason
  118. dict[NSUnderlyingErrorKey] = error
  119. error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
  120. // Replace this with code to handle the error appropriately.
  121. // 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.
  122. NSLog("Unresolved error \(error), \(error!.userInfo)")
  123. abort()
  124. } catch {
  125. fatalError()
  126. }
  127. return coordinator
  128. }()
  129. lazy var managedObjectContext: NSManagedObjectContext? = {
  130. // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
  131. let coordinator = self.persistentStoreCoordinator
  132. if coordinator == nil {
  133. return nil
  134. }
  135. var managedObjectContext = NSManagedObjectContext()
  136. managedObjectContext.persistentStoreCoordinator = coordinator
  137. return managedObjectContext
  138. }()
  139. // MARK: - Core Data Saving support
  140. func saveContext () {
  141. if let moc = self.managedObjectContext {
  142. var error: NSError? = nil
  143. if moc.hasChanges {
  144. do {
  145. try moc.save()
  146. } catch let error1 as NSError {
  147. error = error1
  148. // Replace this implementation with code to handle the error appropriately.
  149. // 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.
  150. NSLog("Unresolved error \(error), \(error!.userInfo)")
  151. abort()
  152. }
  153. }
  154. }
  155. }
  156. }