暂无描述

OnboardingViewController.swift 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. //
  2. // OnboardingViewController.swift
  3. // EncuestaMarle
  4. //
  5. // Created by Tatiana Castro on 5/21/19.
  6. // Copyright © 2019 TANIA. 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. var jsonString_reset = String()
  38. var jsonDict_reset = [String: Any]()
  39. var n_jsonDict_reset = [String: Any]()
  40. var response_reset = String()
  41. func getConsent_task(task: ORKTaskViewController) -> ORKTaskViewController{
  42. return task
  43. }
  44. func limpiarJson_reg(){
  45. let resultados_encuestas = jsonDict_reg["results"] as! [[String:Any]]
  46. if let resultado_pregunta = resultados_encuestas[2]["results"] as? [[String:Any]]{
  47. n_jsonDict_reg["token"]=token
  48. tokenPDF = token
  49. n_jsonDict_reg["email"]=resultado_pregunta[0]["textAnswer"]
  50. n_jsonDict_reg["password"]=resultado_pregunta[1]["textAnswer"]
  51. n_jsonDict_reg["gender"]=resultado_pregunta[3]["choiceAnswers"]
  52. // -------------------------------------------- ☹️ ----------------------------------------------
  53. // Removed due to Apple screwing up the keyboard constraints
  54. //n_jsonDict_reg["job"]=resultado_pregunta[4]["choiceAnswers"]
  55. let date = resultado_pregunta[4]["dateAnswer"] as! String
  56. n_jsonDict_reg["yearBirth"]=date.prefix(4)
  57. }
  58. }
  59. func limpiarJson_recovery(){
  60. let resultados_encuestas = jsonDict_r["results"] as! [[String:Any]]
  61. if let resultado_pregunta = resultados_encuestas[0]["results"] as? [[String:Any]]{
  62. // if let user_token = UserDefaults.standard.string(forKey: "deviceTokenForSNS") {
  63. // //print(stringOne) // Some String Value
  64. // token=user_token
  65. // //response_token=true
  66. // }
  67. // if let user_token = UserDefaults.standard.string(forKey: "user_token") {
  68. // //print(stringOne) // Some String Value
  69. // token=user_token
  70. // //response_token=true
  71. // }
  72. // print("tokenErr"+token);
  73. n_jsonDict_r["token"]=token
  74. n_jsonDict_r["email"]=resultado_pregunta[0]["textAnswer"]
  75. n_jsonDict_r["password"]=resultado_pregunta[1]["textAnswer"]
  76. }
  77. }
  78. //func limpiarJson_reset(){
  79. // let resultados_encuestas = jsonDict_reset["results"] as! [[String:Any]]
  80. // if let resultado_pregunta = resultados_encuestas[0]["results"] as? [[String:Any]]{
  81. // n_jsonDict_reset["email"]=resultado_pregunta[0]["textAnswer"]
  82. // }
  83. //}
  84. func sendEmail(email: String) {
  85. //impiarJson_reset()
  86. let jsonObject: NSMutableDictionary = NSMutableDictionary()
  87. jsonObject.setValue(email, forKey: "email")
  88. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/askForEmail.php")! as URL)
  89. request.httpMethod = "POST"
  90. let jsonData: NSData
  91. do {
  92. jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions()) as NSData
  93. let jsonEmail = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
  94. print("✅ Email recieved, sending request...")
  95. let postString = "data=\(jsonEmail)"
  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 solito Email = \(String(describing: response))") //Error: 1062
  104. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  105. print("responseString Email = \(String(describing: responseString))")
  106. response_reset = responseString as! String
  107. }
  108. task.resume()
  109. } catch {
  110. print ("❌ JSON Failure")
  111. }
  112. }
  113. func sendJson_reg() {
  114. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/registration.php")! as URL)
  115. request.httpMethod = "POST"
  116. let postString = "data=\(jsonString_reg)"
  117. print("json Sign-Up ✅")
  118. request.httpBody = postString.data(using: String.Encoding.utf8)
  119. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  120. data, response, error in
  121. if error != nil {
  122. print("error=\(String(describing: error))")
  123. return
  124. }
  125. print("response solito Sign Up = \(String(describing: response))") //Error: 1062
  126. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  127. print("responseString Sign Up = \(String(describing: responseString))")
  128. response_reg = responseString! as String
  129. }
  130. task.resume()
  131. }
  132. func sendJson_r() {
  133. limpiarJson_recovery()
  134. do {
  135. let jsonData_r = try JSONSerialization.data(withJSONObject: n_jsonDict_r, options: .prettyPrinted)
  136. jsonString_r = NSString(data: jsonData_r, encoding: String.Encoding.utf8.rawValue)! as String
  137. }
  138. catch {
  139. print(error.localizedDescription)
  140. }
  141. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/recoverAccount.php")! as URL)
  142. request.httpMethod = "POST"
  143. let postString = "data=\(jsonString_r)"
  144. request.httpBody = postString.data(using: String.Encoding.utf8)
  145. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  146. data, response, error in
  147. if error != nil {
  148. print("error=\(String(describing: error))")
  149. return
  150. }
  151. print("response Recover Account ⚠️ solito = \(String(describing: response))") //Error: 1062
  152. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  153. print("response Recover Account ⚠️ reg= \(String(describing: responseString))")
  154. response_r = responseString as! String
  155. // REMEMBER TO PRESENT ERRORS BASED ON RESPONSE (EMAIL MAL OR PW MAL)
  156. }
  157. task.resume()
  158. }
  159. func sendPDF(_ base64EncodedPDF: String, _ date: Date) {
  160. if sentPDF == false {
  161. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/getSignatureIOS2.php")! as URL)
  162. request.httpMethod = "POST"
  163. // let jsonObject1: [String: Any] = [
  164. // "data": [
  165. // "signaturePDFBase64": base64EncodedPDF,
  166. // "signatureDate": date,
  167. // "token": tokenPDF
  168. // ],
  169. // ]
  170. let jsonObject: NSMutableDictionary = NSMutableDictionary()
  171. jsonObject.setValue(base64EncodedPDF, forKey: "signaturePDFBase64")
  172. jsonObject.setValue(date.description, forKey: "signatureDate")
  173. jsonObject.setValue(tokenPDF, forKey: "token")
  174. print("Date is formatted as: 📆")
  175. print(date.description)
  176. let jsonData: NSData
  177. do {
  178. jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions()) as NSData
  179. let jsonString_PDF = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
  180. print("✅ jsonPDF Created, sending request...")
  181. let postString = "data=\(jsonString_PDF)"
  182. request.httpBody = postString.data(using: String.Encoding.utf8)
  183. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  184. data, response, error in
  185. if error != nil {
  186. print("error=\(String(describing: error))")
  187. return
  188. }
  189. print("response solito PDF = \(String(describing: response))") //Error: 1062
  190. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  191. print("responseString PDF = \(String(describing: responseString))")
  192. response_PDF = responseString as! String
  193. }
  194. sentPDF = true
  195. task.resume()
  196. } catch {
  197. print ("❌ JSON Failure")
  198. }
  199. }
  200. }
  201. class OnboardingViewController: UIViewController {
  202. @IBAction func joinButtonTapped(_ sender: UIButton) {
  203. let consentStep = ORKVisualConsentStep(identifier: "VisualConsentStep", document: consentDocument)
  204. let registrationTitle = NSLocalizedString("Registration", comment: "")
  205. let passcodeValidationRegularExpressionPattern = "^(?=.*\\d).{4,8}$"
  206. let passcodeValidationRegularExpression = try! NSRegularExpression(pattern: passcodeValidationRegularExpressionPattern)
  207. let passcodeInvalidMessage = NSLocalizedString("A valid password must be 4 to 8 characters long and include at least one numeric character.", comment: "")
  208. // Apple removed .includeJob so I removed from the middle possition here
  209. let registrationOptions: ORKRegistrationStepOption = [.includeGender, .includeDOB]
  210. let registrationStep = ORKRegistrationStep(identifier: "registration", title: registrationTitle, text: "Register for TANIA Study", passcodeValidationRegularExpression: passcodeValidationRegularExpression, passcodeInvalidMessage: passcodeInvalidMessage, options: registrationOptions)
  211. let signature = consentDocument.signatures!.first!
  212. let reviewConsentStep = ORKConsentReviewStep(identifier: "ConsentReviewStep", signature: signature, in: consentDocument)
  213. reviewConsentStep.text = "Review the consent form."
  214. reviewConsentStep.reasonForConsent = "Consent to join the TANIA Study."
  215. let passcodeStep = ORKPasscodeStep(identifier: "Passcode")
  216. passcodeStep.text = "Now you will create a passcode to identify yourself to the app and protect access to information you've entered."
  217. let completionStep = ORKCompletionStep(identifier: "CompletionStep")
  218. completionStep.title = "Welcome aboard."
  219. completionStep.text = "Thank you for joining this study."
  220. print("checko")
  221. task_def = "registration"
  222. let orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, registrationStep])
  223. let taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  224. taskViewController.delegate = self
  225. if response_reg == "Error:Email"{
  226. let orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, registrationStep])
  227. let taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  228. taskViewController.delegate = self
  229. present(taskViewController, animated: true){
  230. let alertTitle = NSLocalizedString("Error: Email Already Registered", comment: "")
  231. let alertMessage = NSLocalizedString("Exit and try recovering your account", comment: "")
  232. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  233. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  234. taskViewController.present(alert, animated: true, completion: nil)
  235. self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  236. }
  237. }
  238. else if response_reg == "Error:Token"{
  239. let orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, registrationStep])
  240. let taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  241. taskViewController.delegate = self
  242. present(taskViewController, animated: true){
  243. let alertTitle = NSLocalizedString("Error: Phone Already Used", comment: "")
  244. let alertMessage = NSLocalizedString("This phone has been used to create an account already. Please contact your mentor.", comment: "")
  245. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  246. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  247. taskViewController.present(alert, animated: true, completion: nil)
  248. self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  249. }
  250. }
  251. else{
  252. let c_orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, registrationStep, completionStep])
  253. let c_taskViewController = ORKTaskViewController(task: c_orderedTask, taskRun: nil)
  254. c_taskViewController.delegate = self
  255. present(c_taskViewController, animated: true, completion: nil)
  256. let taskViewController = ORKTaskViewController(task: EncuestaMarle, taskRun: nil)
  257. taskViewController.delegate = (self as ORKTaskViewControllerDelegate)
  258. present(taskViewController, animated: true, completion: nil)
  259. }
  260. }
  261. @IBAction func recover_account(_ sender: UIButton) {
  262. class LoginViewController : ORKLoginStepViewController {
  263. override func forgotPasswordButtonTapped() {
  264. var email: String = ""
  265. let alertTitle = NSLocalizedString("Enter your email", comment: "")
  266. let alertMessage = NSLocalizedString("You will recieve instructions to reset your password.", comment: "")
  267. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  268. alert.addTextField { (textField) in
  269. textField.placeholder = "Email"
  270. }
  271. alert.addAction(UIAlertAction(title: "Submit", style: UIAlertAction.Style.default, handler: { [weak alert] (_) in
  272. let textField = alert!.textFields![0] // Force unwrapping because we know it exists.
  273. print("Text field email: \(String(describing: textField.text))")
  274. email = textField.text!
  275. sendEmail(email: email)
  276. let alertTitle2 = NSLocalizedString("If the email is registered we will send you an email", comment: "")
  277. let alertMessage2 = NSLocalizedString("Check \(email) for instructions to reset your password", comment: "")
  278. let alert2 = UIAlertController(title: alertTitle2, message: alertMessage2, preferredStyle: UIAlertController.Style.alert)
  279. alert2.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  280. self.present(alert2, animated: true, completion: nil)
  281. }))
  282. alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel , handler: nil))
  283. self.present(alert, animated: true, completion: nil)
  284. }
  285. }
  286. let loginTitle = NSLocalizedString("Recover Account", comment: "")
  287. let loginStep = ORKLoginStep(identifier: "recover" , title: loginTitle, text: "Fill out information to recover account", loginViewControllerClass: LoginViewController.self)
  288. let orderedTask = ORKOrderedTask(identifier: "Join", steps: [loginStep])
  289. let taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  290. taskViewController.delegate = self
  291. if (resetPassword) {
  292. task_def = "reset"
  293. resetPassword = false
  294. let alertTitle2 = NSLocalizedString("Email will arrive soon", comment: "")
  295. let alertMessage2 = NSLocalizedString("Check your inbox for instructions to reset your password", comment: "")
  296. let alert2 = UIAlertController(title: alertTitle2, message: alertMessage2, preferredStyle: UIAlertController.Style.alert)
  297. alert2.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  298. self.present(alert2, animated: true, completion: nil)
  299. }
  300. else {
  301. task_def = "recover"
  302. }
  303. present(taskViewController, animated: true, completion: nil)
  304. }
  305. }
  306. extension OnboardingViewController : ORKTaskViewControllerDelegate {
  307. public func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
  308. switch reason {
  309. case .completed:
  310. if task_def == "reset" {
  311. let taskResult_reset = taskViewController.result
  312. let jsonData_reset = try! ORKESerializer.jsonData(for: taskResult_reset)
  313. jsonString_reset = NSString(data: jsonData_reset, encoding: String.Encoding.utf8.rawValue)! as String
  314. jsonDict_reset = convertToDictionary(text: jsonString_r as String) as! [String: Any]
  315. do {
  316. let jsonData_reset = try JSONSerialization.data(withJSONObject: jsonDict_reset, options: .prettyPrinted)
  317. jsonString_reset = NSString(data: jsonData_reset, encoding: String.Encoding.utf8.rawValue)! as String
  318. }
  319. catch {
  320. print(error.localizedDescription)
  321. }
  322. //sendEmail()
  323. }
  324. else if task_def == "recover"{
  325. let taskResult_r = taskViewController.result
  326. let jsonData_r = try! ORKESerializer.jsonData(for: taskResult_r)
  327. jsonString_r = NSString(data: jsonData_r, encoding: String.Encoding.utf8.rawValue)! as String
  328. jsonDict_r = convertToDictionary(text: jsonString_r as String) as! [String: Any]
  329. do {
  330. let jsonData_r = try JSONSerialization.data(withJSONObject: jsonDict_r, options: .prettyPrinted)
  331. jsonString_r = NSString(data: jsonData_r, encoding: String.Encoding.utf8.rawValue)! as String
  332. }
  333. catch {
  334. print(error.localizedDescription)
  335. }
  336. sendJson_r()
  337. // TODO:
  338. // THIS REPRESENTS HOW TO RESPOND TO WRONG INPUT
  339. while(newResponseR == false) {}
  340. newResponseR = false
  341. // implement if (resetPassword == true) workflow
  342. if (response_r == "Error:hash" || response_r == "Error:password" || response_r == "Error:Email") {
  343. let alertTitle = NSLocalizedString("Email and Password do not match", comment: "")
  344. let alertMessage = NSLocalizedString("Try again or tap forgot password.", comment: "")
  345. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  346. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  347. taskViewController.present(alert, animated: true, completion: nil)
  348. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  349. }
  350. else if response_r == "Error:token"{
  351. let alertTitle = NSLocalizedString("Phone already registered", comment: "")
  352. 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: "")
  353. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  354. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  355. taskViewController.present(alert, animated: true, completion: nil)
  356. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  357. }
  358. else if response_r == "Error:1048\n"{
  359. let alertTitle = NSLocalizedString("Problem with emulation", comment: "")
  360. let alertMessage = NSLocalizedString("You need a physical device to run this application. It can not be run from the emulator because it needs to acquire an Amazon SNS token.", comment: "")
  361. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  362. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  363. taskViewController.present(alert, animated: true, completion: nil)
  364. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  365. }
  366. else {
  367. UserDefaults.standard.set(true, forKey: "registered")
  368. UserDefaults.standard.synchronize()
  369. // MARK: Restore PDF here
  370. // let decodedData = Data(base64Encoded: base64Encoded)!
  371. let decodedString = Data(base64Encoded: response_r)!
  372. // let decodedString = String(data: decodedData, encoding: .utf8)!
  373. var docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last as NSURL?
  374. docURL = docURL?.appendingPathComponent("ConsentDocument.pdf") as NSURL?
  375. do {
  376. try decodedString.write(to:docURL! as URL)
  377. print("PDF written to disk from recovery ✅")
  378. print(docURL! as URL)
  379. } catch let error {
  380. print("❌")
  381. print(error.localizedDescription)
  382. }
  383. performSegue(withIdentifier: "unwindToStudy", sender: nil)
  384. }
  385. }
  386. else{
  387. let taskResult_reg = taskViewController.result
  388. if let stepResult = taskResult_reg.stepResult(forStepIdentifier: "ConsentReviewStep"),
  389. let signatureResult = stepResult.results?.first as? ORKConsentSignatureResult {
  390. print("Signature generated ✅")
  391. print(signatureResult)
  392. let signatureDate = signatureResult.endDate
  393. // lets try to make a pdf for this
  394. let documentCopy = consentDocument
  395. signatureResult.apply(to: documentCopy)
  396. documentCopy.makePDF { (data, error) -> Void in
  397. var docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last as NSURL?
  398. docURL = docURL?.appendingPathComponent("ConsentDocument.pdf") as NSURL?
  399. do {
  400. try data?.write(to:docURL! as URL)
  401. print("PDF written to disk ✅")
  402. print(docURL! as URL)
  403. if let pdfBase64 = data?.base64EncodedString() {
  404. sendPDF(pdfBase64, signatureDate)
  405. }
  406. } catch let error {
  407. print("❌")
  408. print(error.localizedDescription)
  409. }
  410. }
  411. // let sigJson = try! ORKESerializer.jsonData(for: signatureResult)
  412. // print(sigJson.base64EncodedString())
  413. }
  414. let jsonData_reg = try! ORKESerializer.jsonData(for: taskResult_reg)
  415. jsonString_reg = NSString(data: jsonData_reg, encoding: String.Encoding.utf8.rawValue)! as String
  416. jsonDict_reg = convertToDictionary(text: jsonString_reg as String) as! [String: Any]
  417. limpiarJson_reg()
  418. do {
  419. let jsonData_reg = try JSONSerialization.data(withJSONObject: n_jsonDict_reg, options: .prettyPrinted)
  420. jsonString_reg = NSString(data: jsonData_reg, encoding: String.Encoding.utf8.rawValue)! as String
  421. }
  422. catch {
  423. print(error.localizedDescription)
  424. }
  425. // TODO:
  426. // MAYBE THIS DOES IT BETTER
  427. sendJson_reg()
  428. while(newResponseReg == false) {}
  429. newResponseReg = false
  430. if response_reg == "Error:email"{
  431. let alertTitle = NSLocalizedString("Email Already Registered", comment: "")
  432. let alertMessage = NSLocalizedString("Exit and try recovering your account", comment: "")
  433. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  434. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  435. taskViewController.present(alert, animated: true, completion: nil)
  436. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  437. }
  438. else if response_reg == "Error:token"{
  439. let alertTitle = NSLocalizedString("Phone Already Used", comment: "")
  440. let alertMessage = NSLocalizedString("This phone has been used to create an account already. Please contact your mentor.", comment: "")
  441. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  442. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  443. taskViewController.present(alert, animated: true, completion: nil)
  444. //self.performSegue(withIdentifier: "toOnboarding", sender: nil)
  445. }
  446. else{
  447. UserDefaults.standard.set(true, forKey: "registered")
  448. UserDefaults.standard.synchronize()
  449. // let vc = ResearchContainerViewController()
  450. // self.present(vc, animated: true, completion: nil)
  451. performSegue(withIdentifier: "unwindToStudy", sender: nil)
  452. // performSegue(withIdentifier: "toStudy2", sender: self)
  453. }
  454. // else{
  455. // present(taskViewController, animated: true){
  456. // let completionStep = ORKCompletionStep(identifier: "CompletionStep")
  457. // completionStep.title = "Welcome aboard."
  458. // completionStep.text = "Thank you for joining this study."
  459. // let orderedTask = ORKOrderedTask(identifier: "Join", steps: [completionStep])
  460. // let c_taskViewController = ORKTaskViewController(task: orderedTask, taskRun: nil)
  461. // c_taskViewController.delegate = self
  462. // taskViewController.present(c_taskViewController, animated: true)
  463. // }
  464. // }
  465. }
  466. case .discarded, .failed, .saved:
  467. dismiss(animated: true, completion: nil)
  468. }
  469. }
  470. }
  471. @IBDesignable extension UIButton {
  472. @IBInspectable var borderWidth: CGFloat {
  473. set {
  474. layer.borderWidth = newValue
  475. }
  476. get {
  477. return layer.borderWidth
  478. }
  479. }
  480. @IBInspectable var cornerRadius: CGFloat {
  481. set {
  482. layer.cornerRadius = newValue
  483. }
  484. get {
  485. return layer.cornerRadius
  486. }
  487. }
  488. @IBInspectable var borderColor: UIColor? {
  489. set {
  490. guard let uiColor = newValue else { return }
  491. layer.borderColor = uiColor.cgColor
  492. }
  493. get {
  494. guard let color = layer.borderColor else { return nil }
  495. return UIColor(cgColor: color)
  496. }
  497. }
  498. }
  499. //extension NSLayoutConstraint {
  500. //
  501. // override public var description: String {
  502. // let id = identifier ?? ""
  503. // return "id: \(id), constant: \(constant)" //you may print whatever you want here
  504. // }
  505. //}
  506. extension ORKTaskViewController {
  507. override open func viewDidLoad() {
  508. super.viewDidLoad()
  509. if #available(iOS 13, *) {
  510. overrideUserInterfaceStyle = .light
  511. }
  512. }
  513. }