Bez popisu

AppDelegate.swift 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. //
  2. // AppDelegate.swift
  3. // EncuestaMarle
  4. //
  5. // Created by Tatiana Castro on 4/13/19.
  6. // Copyright © 2019 Marle. All rights reserved.
  7. //
  8. import UIKit
  9. import CoreData
  10. import AWSSNS
  11. import UserNotifications
  12. import Firebase
  13. import ResearchKit
  14. @UIApplicationMain
  15. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
  16. let SNSPlatformApplicationArn = "arn:aws:sns:us-east-1:227586183436:app/APNS_SANDBOX/MARLE_iOS"
  17. var containerViewController: ResearchContainerViewController? {
  18. return window?.rootViewController as? ResearchContainerViewController
  19. }
  20. var window: UIWindow?
  21. func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
  22. let standardDefaults = UserDefaults.standard
  23. if standardDefaults.object(forKey: "EncuestaMarleFirstRun") == nil {
  24. standardDefaults.setValue("EncuestaMarleFirstRun", forKey: "EncuestaMarleFirstRun")
  25. }
  26. UserDefaults.standard.set(false, forKey: "registered")
  27. let pageControlAppearance = UIPageControl.appearance()
  28. pageControlAppearance.pageIndicatorTintColor = UIColor.lightGray
  29. pageControlAppearance.currentPageIndicatorTintColor = UIColor.black
  30. return true
  31. }
  32. func applicationDidEnterBackground(_ application: UIApplication) {
  33. if ORKPasscodeViewController.isPasscodeStoredInKeychain() {
  34. // Hide content so it doesn't appear in the app switcher.
  35. containerViewController?.contentHidden = true
  36. }
  37. }
  38. func applicationWillEnterForeground(_ application: UIApplication) {
  39. }
  40. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  41. let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.USEast1, identityPoolId:"us-east-1:b8e84ae3-42e8-4655-a70e-1dcd8d053db5")
  42. let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider)
  43. AWSServiceManager.default().defaultServiceConfiguration = configuration
  44. registerForPushNotifications(application: application)
  45. return true
  46. }
  47. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  48. token = ""
  49. for i in 0..<deviceToken.count {
  50. token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
  51. }
  52. print(token)
  53. UserDefaults.standard.set(token, forKey: "deviceTokenForSNS")
  54. let sns = AWSSNS.default()
  55. let request = AWSSNSCreatePlatformEndpointInput()
  56. request?.token = token
  57. request?.platformApplicationArn = SNSPlatformApplicationArn
  58. sns.createPlatformEndpoint(request!).continueWith(executor: AWSExecutor.mainThread(), block: { (task: AWSTask!) -> AnyObject? in
  59. if task.error != nil {
  60. print("Error: \(String(describing: task.error))")
  61. } else {
  62. let createEndpointResponse = task.result! as AWSSNSCreateEndpointResponse
  63. if let endpointArnForSNS = createEndpointResponse.endpointArn {
  64. print("endpointArn: \(endpointArnForSNS)")
  65. UserDefaults.standard.set(endpointArnForSNS, forKey: "endpointArnForSNS")
  66. UserDefaults.standard.set(token, forKey: "user_token")
  67. }
  68. }
  69. return nil
  70. })
  71. }
  72. func registerForPushNotifications(application: UIApplication) {
  73. if #available(iOS 10.0, *) {
  74. UNUserNotificationCenter.current().delegate = self
  75. UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
  76. if (granted)
  77. {
  78. UIApplication.shared.registerForRemoteNotifications()
  79. }
  80. else{
  81. }
  82. })
  83. } else {
  84. let settings = UIUserNotificationSettings(types: [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound], categories: nil)
  85. application.registerUserNotificationSettings(settings)
  86. application.registerForRemoteNotifications()
  87. }
  88. }
  89. @available(iOS 10.0, *)
  90. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  91. print("User Info = ",notification.request.content.userInfo)
  92. completionHandler([.alert, .badge, .sound])
  93. }
  94. @available(iOS 10.0, *)
  95. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  96. print("User Info = ",response.notification.request.content.userInfo)
  97. completionHandler()
  98. }
  99. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  100. print(error.localizedDescription)
  101. }
  102. func applicationWillResignActive(_ application: UIApplication) {
  103. // 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.
  104. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  105. }
  106. func applicationDidBecomeActive(_ application: UIApplication) {
  107. // 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.
  108. getJsonFromUrl()
  109. }
  110. func applicationWillTerminate(_ application: UIApplication) {
  111. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  112. // Saves changes in the application's managed object context before the application terminates.
  113. self.saveContext()
  114. }
  115. // MARK: - Core Data stack
  116. lazy var persistentContainer: NSPersistentContainer = {
  117. /*
  118. The persistent container for the application. This implementation
  119. creates and returns a container, having loaded the store for the
  120. application to it. This property is optional since there are legitimate
  121. error conditions that could cause the creation of the store to fail.
  122. */
  123. let container = NSPersistentContainer(name: "EncuestaMarle")
  124. container.loadPersistentStores(completionHandler: { (storeDescription, error) in
  125. if let error = error as NSError? {
  126. // Replace this implementation with code to handle the error appropriately.
  127. // 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.
  128. /*
  129. Typical reasons for an error here include:
  130. * The parent directory does not exist, cannot be created, or disallows writing.
  131. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  132. * The device is out of space.
  133. * The store could not be migrated to the current model version.
  134. Check the error message to determine what the actual problem was.
  135. */
  136. fatalError("Unresolved error \(error), \(error.userInfo)")
  137. }
  138. })
  139. return container
  140. }()
  141. // MARK: - Core Data Saving support
  142. func saveContext () {
  143. let context = persistentContainer.viewContext
  144. if context.hasChanges {
  145. do {
  146. try context.save()
  147. } catch {
  148. // Replace this implementation with code to handle the error appropriately.
  149. // 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.
  150. let nserror = error as NSError
  151. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  152. }
  153. }
  154. }
  155. }
  156. extension AppDelegate: ORKPasscodeDelegate {
  157. func passcodeViewControllerDidFinish(withSuccess viewController: UIViewController) {
  158. containerViewController?.contentHidden = false
  159. viewController.dismiss(animated: true, completion: nil)
  160. }
  161. func passcodeViewControllerDidFailAuthentication(_ viewController: UIViewController) {
  162. }
  163. }