Açıklama Yok

AppDelegate.swift 9.6KB

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