暫無描述

OnboardingViewController.swift 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. //
  2. // OnboardingViewController.swift
  3. // EncuestaMarle
  4. //
  5. // Created by Tatiana Castro on 5/21/19.
  6. // Copyright © 2019 Marle. All rights reserved.
  7. //
  8. import UIKit
  9. import ResearchKit
  10. var jsonDict_reg = [String: Any]()
  11. var n_jsonDict_reg = [String: Any]()
  12. var jsonDict_r = [String: Any]()
  13. var n_jsonDict_r = [String: Any]()
  14. var jsonString_reg = String()
  15. var jsonString_r = String()
  16. var jsonData_reg = Data()
  17. var newResponseReg: Bool = false
  18. var response_reg: String = "" {
  19. didSet {
  20. newResponseReg = true
  21. }
  22. }
  23. var newResponseR: Bool = false
  24. var response_r: String = "" {
  25. didSet {
  26. newResponseR = true
  27. }
  28. }
  29. var task = ORKTaskViewController()
  30. var consentDocument = ConsentDocument()
  31. var task_def = String()
  32. var sentPDF: Bool = false
  33. var jsonPDF = String()
  34. var response_PDF = String()
  35. var tokenPDF = String()
  36. var resetPassword: Bool = false
  37. func getConsent_task(task: ORKTaskViewController) -> ORKTaskViewController{
  38. return task
  39. }
  40. func limpiarJson_reg(){
  41. let resultados_encuestas = jsonDict_reg["results"] as! [[String:Any]]
  42. if let resultado_pregunta = resultados_encuestas[2]["results"] as? [[String:Any]]{
  43. n_jsonDict_reg["token"]=token
  44. tokenPDF = token
  45. n_jsonDict_reg["email"]=resultado_pregunta[0]["textAnswer"]
  46. n_jsonDict_reg["password"]=resultado_pregunta[1]["textAnswer"]
  47. n_jsonDict_reg["gender"]=resultado_pregunta[3]["choiceAnswers"]
  48. // -------------------------------------------- ☹️ ----------------------------------------------
  49. // Removed due to Apple screwing up the keyboard constraints
  50. n_jsonDict_reg["job"]=resultado_pregunta[4]["choiceAnswers"]
  51. let date = resultado_pregunta[5]["dateAnswer"] as! String
  52. n_jsonDict_reg["yearBirth"]=date.prefix(4)
  53. }
  54. }
  55. func limpiarJson_recovery(){
  56. let resultados_encuestas = jsonDict_r["results"] as! [[String:Any]]
  57. if let resultado_pregunta = resultados_encuestas[0]["results"] as? [[String:Any]]{
  58. n_jsonDict_r["token"]=token
  59. n_jsonDict_r["email"]=resultado_pregunta[0]["textAnswer"]
  60. n_jsonDict_r["password"]=resultado_pregunta[1]["textAnswer"]
  61. }
  62. }
  63. func sendJson_reg() {
  64. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/registration.php")! as URL)
  65. request.httpMethod = "POST"
  66. let postString = "data=\(jsonString_reg)"
  67. print("json Sign-Up ✅")
  68. request.httpBody = postString.data(using: String.Encoding.utf8)
  69. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  70. data, response, error in
  71. if error != nil {
  72. print("error=\(String(describing: error))")
  73. return
  74. }
  75. print("response solito Sign Up = \(String(describing: response))") //Error: 1062
  76. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  77. print("responseString Sign Up = \(String(describing: responseString))")
  78. response_reg = responseString! as String
  79. }
  80. task.resume()
  81. }
  82. func sendJson_r() {
  83. limpiarJson_recovery()
  84. do {
  85. let jsonData_r = try JSONSerialization.data(withJSONObject: n_jsonDict_r, options: .prettyPrinted)
  86. jsonString_r = NSString(data: jsonData_r, encoding: String.Encoding.utf8.rawValue)! as String
  87. }
  88. catch {
  89. print(error.localizedDescription)
  90. }
  91. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/recoverAccount.php")! as URL)
  92. request.httpMethod = "POST"
  93. print("Json Log-In ✅ 👀")
  94. print(jsonString_r)
  95. let postString = "data=\(jsonString_r)"
  96. request.httpBody = postString.data(using: String.Encoding.utf8)
  97. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  98. data, response, error in
  99. if error != nil {
  100. print("error=\(String(describing: error))")
  101. return
  102. }
  103. print("response Recover Account ⚠️ solito = \(String(describing: response))") //Error: 1062
  104. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  105. print("response Recover Account ⚠️ reg= \(String(describing: responseString))")
  106. response_r = responseString as! String
  107. // REMEMBER TO PRESENT ERRORS BASED ON RESPONSE (EMAIL MAL OR PW MAL)
  108. }
  109. task.resume()
  110. }
  111. func sendPDF(_ base64EncodedPDF: String, _ date: Date) {
  112. if sentPDF == false {
  113. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/getSignatureIOS2.php")! as URL)
  114. request.httpMethod = "POST"
  115. // let jsonObject1: [String: Any] = [
  116. // "data": [
  117. // "signaturePDFBase64": base64EncodedPDF,
  118. // "signatureDate": date,
  119. // "token": tokenPDF
  120. // ],
  121. // ]
  122. let jsonObject: NSMutableDictionary = NSMutableDictionary()
  123. jsonObject.setValue(base64EncodedPDF, forKey: "signaturePDFBase64")
  124. jsonObject.setValue(date.description, forKey: "signatureDate")
  125. jsonObject.setValue(tokenPDF, forKey: "token")
  126. let jsonData: NSData
  127. do {
  128. jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions()) as NSData
  129. let jsonString_PDF = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
  130. print("✅ jsonPDF Created, sending request...")
  131. let postString = "data=\(jsonString_PDF)"
  132. request.httpBody = postString.data(using: String.Encoding.utf8)
  133. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  134. data, response, error in
  135. if error != nil {
  136. print("error=\(String(describing: error))")
  137. return
  138. }
  139. print("response solito PDF = \(String(describing: response))") //Error: 1062
  140. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  141. print("responseString PDF = \(String(describing: responseString))")
  142. response_PDF = responseString as! String
  143. }
  144. sentPDF = true
  145. task.resume()
  146. } catch {
  147. print ("❌ JSON Failure")
  148. }
  149. }
  150. }
  151. class OnboardingViewController: UIViewController {
  152. @IBAction func joinButtonTapped(_ sender: UIButton) {
  153. let consentStep = ORKVisualConsentStep(identifier: "VisualConsentStep", document: consentDocument)
  154. let registrationTitle = NSLocalizedString("Registration", comment: "")
  155. let passcodeValidationRegularExpressionPattern = "^(?=.*\\d).{4,8}$"
  156. let passcodeValidationRegularExpression = try! NSRegularExpression(pattern: passcodeValidationRegularExpressionPattern)
  157. let passcodeInvalidMessage = NSLocalizedString("A valid password must be 4 to 8 characters long and include at least one numeric character.", comment: "")
  158. let registrationOptions: ORKRegistrationStepOption = [.includeGender, .includeJob, .includeDOB]
  159. let registrationStep = ORKRegistrationStep(identifier: "registration", title: registrationTitle, text: "Register for MARLE Study", passcodeValidationRegularExpression: passcodeValidationRegularExpression, passcodeInvalidMessage: passcodeInvalidMessage, options: registrationOptions)
  160. let signature = consentDocument.signatures!.first!
  161. let reviewConsentStep = ORKConsentReviewStep(identifier: "ConsentReviewStep", signature: signature, in: consentDocument)
  162. reviewConsentStep.text = "Review the consent form."
  163. reviewConsentStep.reasonForConsent = "Consent to join the MARLE Study."
  164. let passcodeStep = ORKPasscodeStep(identifier: "Passcode")
  165. passcodeStep.text = "Now you will create a passcode to identify yourself to the app and protect access to information you've entered."
  166. let completionStep = ORKCompletionStep(identifier: "CompletionStep")
  167. completionStep.title = "Welcome aboard."
  168. completionStep.text = "Thank you for joining this study."
  169. print("checko")
  170. task_def = "registration"
  171. let orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, registrationStep])
  172. let taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  173. taskViewController.delegate = self
  174. if response_reg == "Error:Email"{
  175. let orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, registrationStep])
  176. let taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  177. taskViewController.delegate = self
  178. present(taskViewController, animated: true){
  179. let alertTitle = NSLocalizedString("Error: Email Already Registered", comment: "")
  180. let alertMessage = NSLocalizedString("Exit and try recovering your account", comment: "")
  181. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  182. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  183. taskViewController.present(alert, animated: true, completion: nil)
  184. self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  185. }
  186. }
  187. else if response_reg == "Error:Token"{
  188. let orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, registrationStep])
  189. let taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  190. taskViewController.delegate = self
  191. present(taskViewController, animated: true){
  192. let alertTitle = NSLocalizedString("Error: Phone Already Used", comment: "")
  193. let alertMessage = NSLocalizedString("This phone has been used to create an account already. Please contact your mentor.", comment: "")
  194. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  195. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  196. taskViewController.present(alert, animated: true, completion: nil)
  197. self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  198. }
  199. }
  200. else{
  201. let c_orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, registrationStep, completionStep])
  202. let c_taskViewController = ORKTaskViewController(task: c_orderedTask, taskRun: nil)
  203. c_taskViewController.delegate = self
  204. present(c_taskViewController, animated: true, completion: nil)
  205. let taskViewController = ORKTaskViewController(task: EncuestaMarle, taskRun: nil)
  206. taskViewController.delegate = (self as ORKTaskViewControllerDelegate)
  207. present(taskViewController, animated: true, completion: nil)
  208. }
  209. }
  210. @IBAction func recover_account(_ sender: UIButton) {
  211. class LoginViewController : ORKLoginStepViewController {
  212. override func forgotPasswordButtonTapped() {
  213. let alertTitle = NSLocalizedString("Enter your email and click submit", comment: "")
  214. let alertMessage = NSLocalizedString("You will recieve an email to reset your password.", comment: "")
  215. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  216. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  217. self.present(alert, animated: true, completion: nil)
  218. resetPassword = true
  219. }
  220. }
  221. let loginTitle = NSLocalizedString("Recover Account", comment: "")
  222. let loginStep = ORKLoginStep(identifier: "recover" , title: loginTitle, text: "Fill out information to recover account", loginViewControllerClass: LoginViewController.self)
  223. let orderedTask = ORKOrderedTask(identifier: "Join", steps: [loginStep])
  224. let taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  225. taskViewController.delegate = self
  226. task_def = "recover"
  227. present(taskViewController, animated: true, completion: nil)
  228. }
  229. }
  230. extension OnboardingViewController : ORKTaskViewControllerDelegate {
  231. public func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
  232. switch reason {
  233. case .completed:
  234. if task_def == "recover"{
  235. let taskResult_r = taskViewController.result
  236. let jsonData_r = try! ORKESerializer.jsonData(for: taskResult_r)
  237. jsonString_r = NSString(data: jsonData_r, encoding: String.Encoding.utf8.rawValue)! as String
  238. jsonDict_r = convertToDictionary(text: jsonString_r as String) as! [String: Any]
  239. do {
  240. let jsonData_r = try JSONSerialization.data(withJSONObject: jsonDict_r, options: .prettyPrinted)
  241. jsonString_r = NSString(data: jsonData_r, encoding: String.Encoding.utf8.rawValue)! as String
  242. }
  243. catch {
  244. print(error.localizedDescription)
  245. }
  246. sendJson_r()
  247. // TODO:
  248. // THIS REPRESENTS HOW TO RESPOND TO WRONG INPUT
  249. while(newResponseR == false) {}
  250. newResponseR = false
  251. // implement if (resetPassword == true) workflow
  252. if (response_r == "Error:hash" || response_r == "Error:password") {
  253. let alertTitle = NSLocalizedString("Email and Password do not match", comment: "")
  254. let alertMessage = NSLocalizedString("Try again or tap forgot password.", comment: "")
  255. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  256. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  257. taskViewController.present(alert, animated: true, completion: nil)
  258. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  259. }
  260. else if response_r == "Error:token"{
  261. let alertTitle = NSLocalizedString("Phone already registered", comment: "")
  262. let alertMessage = NSLocalizedString("This phone has been used to create an account already. Please contact your mentor and inform them about this error message", comment: "")
  263. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  264. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  265. taskViewController.present(alert, animated: true, completion: nil)
  266. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  267. }
  268. else {
  269. UserDefaults.standard.set(true, forKey: "registered")
  270. UserDefaults.standard.synchronize()
  271. performSegue(withIdentifier: "unwindToStudy", sender: nil)
  272. }
  273. }
  274. else{
  275. let taskResult_reg = taskViewController.result
  276. if let stepResult = taskResult_reg.stepResult(forStepIdentifier: "ConsentReviewStep"),
  277. let signatureResult = stepResult.results?.first as? ORKConsentSignatureResult {
  278. print("Signature generated ✅")
  279. print(signatureResult)
  280. let signatureDate = signatureResult.endDate
  281. // lets try to make a pdf for this
  282. let documentCopy = consentDocument
  283. signatureResult.apply(to: documentCopy)
  284. documentCopy.makePDF { (data, error) -> Void in
  285. var docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last as NSURL?
  286. docURL = docURL?.appendingPathComponent("ConsentDocument.pdf") as NSURL?
  287. do {
  288. try data?.write(to:docURL! as URL)
  289. print("PDF generated ✅")
  290. print(docURL! as URL)
  291. if let pdfBase64 = data?.base64EncodedString() {
  292. sendPDF(pdfBase64, signatureDate)
  293. }
  294. } catch let error {
  295. print("❌")
  296. print(error.localizedDescription)
  297. }
  298. }
  299. // let sigJson = try! ORKESerializer.jsonData(for: signatureResult)
  300. // print(sigJson.base64EncodedString())
  301. }
  302. let jsonData_reg = try! ORKESerializer.jsonData(for: taskResult_reg)
  303. jsonString_reg = NSString(data: jsonData_reg, encoding: String.Encoding.utf8.rawValue)! as String
  304. jsonDict_reg = convertToDictionary(text: jsonString_reg as String) as! [String: Any]
  305. limpiarJson_reg()
  306. do {
  307. let jsonData_reg = try JSONSerialization.data(withJSONObject: n_jsonDict_reg, options: .prettyPrinted)
  308. jsonString_reg = NSString(data: jsonData_reg, encoding: String.Encoding.utf8.rawValue)! as String
  309. }
  310. catch {
  311. print(error.localizedDescription)
  312. }
  313. // TODO:
  314. // MAYBE THIS DOES IT BETTER
  315. sendJson_reg()
  316. while(newResponseReg == false) {}
  317. newResponseReg = false
  318. if response_reg == "Error:email"{
  319. let alertTitle = NSLocalizedString("Email Already Registered", comment: "")
  320. let alertMessage = NSLocalizedString("Exit and try recovering your account", comment: "")
  321. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  322. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  323. taskViewController.present(alert, animated: true, completion: nil)
  324. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  325. }
  326. else if response_reg == "Error:token"{
  327. let alertTitle = NSLocalizedString("Phone Already Used", comment: "")
  328. let alertMessage = NSLocalizedString("This phone has been used to create an account already. Please contact your mentor.", comment: "")
  329. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  330. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  331. taskViewController.present(alert, animated: true, completion: nil)
  332. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  333. }
  334. else{
  335. UserDefaults.standard.set(true, forKey: "registered")
  336. UserDefaults.standard.synchronize()
  337. // let vc = ResearchContainerViewController()
  338. // self.present(vc, animated: true, completion: nil)
  339. performSegue(withIdentifier: "unwindToStudy", sender: nil)
  340. // performSegue(withIdentifier: "toStudy2", sender: self)
  341. }
  342. // else{
  343. // present(taskViewController, animated: true){
  344. // let completionStep = ORKCompletionStep(identifier: "CompletionStep")
  345. // completionStep.title = "Welcome aboard."
  346. // completionStep.text = "Thank you for joining this study."
  347. // let orderedTask = ORKOrderedTask(identifier: "Join", steps: [completionStep])
  348. // let c_taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  349. // c_taskViewController.delegate = self
  350. // taskViewController.present(c_taskViewController, animated: true)
  351. // }
  352. // }
  353. }
  354. case .discarded, .failed, .saved:
  355. dismiss(animated: true, completion: nil)
  356. }
  357. }
  358. }
  359. //extension NSLayoutConstraint {
  360. //
  361. // override public var description: String {
  362. // let id = identifier ?? ""
  363. // return "id: \(id), constant: \(constant)" //you may print whatever you want here
  364. // }
  365. //}