Nav apraksta

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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/Tania-iOS-2020-NEW"
  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: - URL Scheme Support
  156. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  157. let registered = checkIfRegistered()
  158. if !registered {
  159. let alertTitle = NSLocalizedString("Please join Tania first", comment: "")
  160. let alertMessage = NSLocalizedString("Press the 'Join Study' buttton below to register, then open this link again", comment: "")
  161. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  162. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  163. self.window?.rootViewController?.present(alert, animated: true, completion: nil)
  164. return false
  165. }
  166. else {
  167. let host = url.host
  168. // Process the URL.
  169. guard let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
  170. let params = components.queryItems else {
  171. print("Invalid URL or host missing")
  172. let alertTitle = NSLocalizedString("Invalid link or resource", comment: "")
  173. let alertMessage = NSLocalizedString("Please contact your mentor for further assistance", comment: "")
  174. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  175. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  176. self.window?.rootViewController?.present(alert, animated: true, completion: nil)
  177. return false
  178. }
  179. if let id = params.first(where: { $0.name == "id" })?.value {
  180. print("Host = \(host ?? "Error: No host in URL")")
  181. print("Registrating user to experience ID = \(id)")
  182. registerToExperience(id: id)
  183. while(newResponseID == false) {}
  184. newResponseID = false
  185. if response_id == "Error:hash" {
  186. let alertTitle = NSLocalizedString("That experience does not exist", comment: "")
  187. let alertMessage = NSLocalizedString("Please contact your mentor for further assistance", comment: "")
  188. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  189. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  190. self.window?.rootViewController?.present(alert, animated: true, completion: nil)
  191. return false
  192. }
  193. else if response_id == "Success" {
  194. let alertTitle = NSLocalizedString("Sucessful registration to experience", comment: "")
  195. let alertMessage = NSLocalizedString("Surveys will become available to answer", comment: "")
  196. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  197. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  198. self.window?.rootViewController?.present(alert, animated: true, completion: nil)
  199. return true
  200. }
  201. return false
  202. } else {
  203. print("Encuesta id missing")
  204. let alertTitle = NSLocalizedString("Invalid link or experience ID", comment: "")
  205. let alertMessage = NSLocalizedString("Please contact your mentor for further assistance", comment: "")
  206. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  207. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  208. self.window?.rootViewController?.present(alert, animated: true, completion: nil)
  209. return false
  210. }
  211. }
  212. }
  213. // MARK: - Core Data Saving support
  214. func saveContext () {
  215. let context = persistentContainer.viewContext
  216. if context.hasChanges {
  217. do {
  218. try context.save()
  219. } catch {
  220. // Replace this implementation with code to handle the error appropriately.
  221. // 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.
  222. let nserror = error as NSError
  223. fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  224. }
  225. }
  226. }
  227. }
  228. extension AppDelegate: ORKPasscodeDelegate {
  229. func passcodeViewControllerDidFinish(withSuccess viewController: UIViewController) {
  230. containerViewController?.contentHidden = false
  231. viewController.dismiss(animated: true, completion: nil)
  232. }
  233. func passcodeViewControllerDidFailAuthentication(_ viewController: UIViewController) {
  234. }
  235. }
  236. extension UIApplication {
  237. class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
  238. if let tabController = controller as? UITabBarController {
  239. return topViewController(controller: tabController.selectedViewController)
  240. }
  241. if let navController = controller as? UINavigationController {
  242. return topViewController(controller: navController.visibleViewController)
  243. }
  244. if let presented = controller?.presentedViewController {
  245. return topViewController(controller: presented)
  246. }
  247. return controller
  248. }
  249. }
  250. func registerToExperience(id: String) {
  251. let jsonObject: NSMutableDictionary = NSMutableDictionary()
  252. jsonObject.setValue(token, forKey: "token")
  253. jsonObject.setValue(id, forKey: "id_experiencia")
  254. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/inscripcionExperiencia.php")! as URL)
  255. request.httpMethod = "POST"
  256. let jsonData: NSData
  257. do {
  258. jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions()) as NSData
  259. let jsonID = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
  260. print("✅ ID recieved, sending request...")
  261. let postString = "data=\(jsonID)"
  262. request.httpBody = postString.data(using: String.Encoding.utf8)
  263. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  264. data, response, error in
  265. if error != nil {
  266. print("error=\(String(describing: error))")
  267. return
  268. }
  269. print("response solito ID = \(String(describing: response))") //Error: 1062
  270. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  271. print("responseString ID = \(String(describing: responseString))")
  272. response_id = responseString as! String
  273. }
  274. task.resume()
  275. } catch {
  276. print ("❌ JSON Failure")
  277. }
  278. getJsonFromUrl()
  279. }