Sin descripción

EncuestaViewController.swift 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. //
  2. // EncuestaViewController.swift
  3. // Encuesta_MARLE
  4. //
  5. // Created by Tatiana Castro on 1/31/19.
  6. // Copyright © 2019 Tatiana Castro. All rights reserved.
  7. //
  8. import UIKit
  9. import ResearchKit
  10. //let semaphore = DispatchSemaphore(value: -1)
  11. var token = String()
  12. let URL = "http://tania.uprrp.edu/getSubQ2.php?tk="+token;
  13. var preguntas = [String]()
  14. var descripcion = String()
  15. var id_preg = [String]()
  16. var tipo_preg = [String]()
  17. var cantidad_preguntas = Int()
  18. var max_values = [String]()
  19. var max_text = [String]()
  20. var min_text = [String]()
  21. var id_questionario = String()
  22. var jsonString = String()
  23. var jsonDict = [String: Any]()
  24. var n_jsonDict = [String: Any]()
  25. var response_survey = String()
  26. var newResponseID: Bool = false
  27. var response_id: String = "" {
  28. didSet {
  29. newResponseID = true
  30. }
  31. }
  32. func getJsonFromUrl(){
  33. print("entre a getJsonFromUrl ⚠️")
  34. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/getSubQ2.php?tk="+token)! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60)
  35. // let request = NSMutableURLRequest(url: NSURL(string: "http://emaapp.online/getSubQ2.php?tk="+token)! as URL)
  36. request.httpMethod = "POST"
  37. let postString = "data=\(jsonString_reg)"
  38. request.httpBody = postString.data(using: String.Encoding.utf8)
  39. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  40. data, response, error in
  41. if error != nil {
  42. print("error=\(String(describing: error))")
  43. return
  44. }
  45. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  46. if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
  47. if let id = jsonObj!.value(forKey: "id_subquestionnair") as? String {
  48. id_questionario = id
  49. }
  50. if let des = jsonObj!.value(forKey: "description") as? String {
  51. descripcion = des
  52. }
  53. if let cantidad = jsonObj!.value(forKey: "cantidad_preguntas") as? String {
  54. cantidad_preguntas = Int(cantidad) ?? 0
  55. }
  56. if let jsonArray = jsonObj!.value(forKey: "preguntas") as? NSArray {
  57. for subj in jsonArray{
  58. if let subjDict = subj as? NSDictionary {
  59. if let pregunta = subjDict.value(forKey: "premise") {
  60. preguntas.append((pregunta as? String)!)
  61. }
  62. }
  63. if let subjDict = subj as? NSDictionary {
  64. if let id = subjDict.value(forKey: "id_question") {
  65. id_preg.append((id as? String)!)
  66. }
  67. }
  68. if let subjDict = subj as? NSDictionary {
  69. if let tipo = subjDict.value(forKey: "id_type") {
  70. tipo_preg.append((tipo as? String)!)
  71. }
  72. }
  73. if let subjDict = subj as? NSDictionary {
  74. if let val = subjDict.value(forKey: "max_val") {
  75. max_values.append((val as? String)!)
  76. }
  77. }
  78. if let subjDict = subj as? NSDictionary {
  79. if let mx_txt = subjDict.value(forKey: "max_text") {
  80. max_text.append((mx_txt as? String)!)
  81. }
  82. }
  83. if let subjDict = subj as? NSDictionary {
  84. if let mn_txt = subjDict.value(forKey: "min_text") {
  85. min_text.append((mn_txt as? String)!)
  86. }
  87. }
  88. }
  89. }
  90. }
  91. print("getJsonFromUrl response solito = \(String(describing: response))") //Error: 1062
  92. print("getJsonFromUrl responseString = \(String(describing: responseString))")
  93. //if(responseString)
  94. response_survey = responseString! as String
  95. }
  96. task.resume()
  97. // let url = NSURL(string: URL)
  98. // URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
  99. // if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
  100. // print("entre a jsonObj")
  101. // print(jsonObj as Any)
  102. // if let id = jsonObj!.value(forKey: "id_subquestionnair") as? String {
  103. // id_questionario = id
  104. // }
  105. // if let des = jsonObj!.value(forKey: "description") as? String {
  106. // descripcion = des
  107. // }
  108. // if let cantidad = jsonObj!.value(forKey: "cantidad_preguntas") as? String {
  109. // cantidad_preguntas = Int(cantidad) ?? 0
  110. // }
  111. // if let jsonArray = jsonObj!.value(forKey: "preguntas") as? NSArray {
  112. // for subj in jsonArray{
  113. // if let subjDict = subj as? NSDictionary {
  114. // if let pregunta = subjDict.value(forKey: "premise") {
  115. // preguntas.append((pregunta as? String)!)
  116. // }
  117. // }
  118. // if let subjDict = subj as? NSDictionary {
  119. // if let id = subjDict.value(forKey: "id_question") {
  120. // id_preg.append((id as? String)!)
  121. // }
  122. // }
  123. // if let subjDict = subj as? NSDictionary {
  124. // if let tipo = subjDict.value(forKey: "id_type") {
  125. // tipo_preg.append((tipo as? String)!)
  126. // }
  127. // }
  128. // if let subjDict = subj as? NSDictionary {
  129. // if let val = subjDict.value(forKey: "max_val") {
  130. // max_values.append((val as? String)!)
  131. // }
  132. // }
  133. // if let subjDict = subj as? NSDictionary {
  134. // if let mx_txt = subjDict.value(forKey: "max_text") {
  135. // max_text.append((mx_txt as? String)!)
  136. // }
  137. // }
  138. // if let subjDict = subj as? NSDictionary {
  139. // if let mn_txt = subjDict.value(forKey: "min_text") {
  140. // min_text.append((mn_txt as? String)!)
  141. // }
  142. // }
  143. // }
  144. // }
  145. // if error != nil {
  146. // print("error=\(String(describing: error))")
  147. // return
  148. // }
  149. // print("response = \(String(describing: response))")
  150. // let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  151. // print("responseString = \(String(describing: responseString))")
  152. // response_survey = responseString! as String
  153. // }
  154. // }).resume()
  155. // semaphore.signal()
  156. //semaphore.wait(semaphore,)
  157. // dispatch_semaphore_wait(semaphore,dispatch_time_t(DispatchTime.distantFuture))
  158. }
  159. func sendJson(){
  160. let request = NSMutableURLRequest(url: NSURL(string: "http://tania.uprrp.edu/parseAnswers2.php")! as URL)
  161. request.httpMethod = "POST"
  162. let postString = "data=\(jsonString)"
  163. request.httpBody = postString.data(using: String.Encoding.utf8)
  164. let task = URLSession.shared.dataTask(with: request as URLRequest) {
  165. data, response, error in
  166. if error != nil {
  167. print("error=\(String(describing: error))")
  168. return
  169. }
  170. print("response Answer Parse ✅ = \(String(describing: response))")
  171. let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  172. print("responseString Answer Parse ✅ = \(String(describing: responseString))")
  173. }
  174. task.resume()
  175. }
  176. func convertToDictionary(text: String) -> [String: Any]? {
  177. if let data = text.data(using: .utf8) {
  178. do {
  179. return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
  180. } catch {
  181. print(error.localizedDescription)
  182. }
  183. }
  184. return nil
  185. }
  186. func limpiarJson()->Dictionary<String, Any>{
  187. var data = [String:Any]()
  188. n_jsonDict["token"]=String(token)
  189. n_jsonDict["os"]="ios"
  190. let resultados_encuestas = jsonDict["results"] as! [[String:Any]]
  191. for i in 0..<cantidad_preguntas{
  192. if let resultado_pregunta = resultados_encuestas[i]["results"] as? [[String:Any]],
  193. var resultado = resultado_pregunta.first {
  194. data["startDate"] = resultado["startDate"]
  195. data["identifier"] = resultado["identifier"]
  196. data["questionType"] = resultado["questionType"]
  197. data["choiceAnswers"] = resultado["choiceAnswers"]
  198. data["endDate"] = resultado["endDate"]
  199. }
  200. n_jsonDict["pregunta"+String(i+1)+"resultados"] = data
  201. }
  202. n_jsonDict["id_subquestionnair"]=jsonDict["identifier"]
  203. return n_jsonDict
  204. }
  205. class EncuestaViewController: UIViewController {
  206. @IBAction func tomar_encuesta(_ sender: UIButton) {
  207. //getJsonFromUrl()
  208. //semaphore.wait()
  209. if response_survey == "Error:NoHay"{
  210. let alertTitle = NSLocalizedString("No Survey", comment: "")
  211. let alertMessage = NSLocalizedString("There is no survey available right now. Please register to an experience or check back later.", comment: "")
  212. let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
  213. alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
  214. self.present(alert, animated: true, completion: nil)
  215. }
  216. else{
  217. let taskViewController = ORKTaskViewController(task: EncuestaMarle, taskRun: nil)
  218. taskViewController.delegate = (self as ORKTaskViewControllerDelegate)
  219. present(taskViewController, animated: true, completion: nil)
  220. //print("voy a llamar getJsonFromUrl desde controller")
  221. //getJsonFromUrl()
  222. }
  223. }
  224. override func viewDidLoad() {
  225. super.viewDidLoad()
  226. print("voy a llamar getJsonFromUrl")
  227. getJsonFromUrl()
  228. //semaphore.signal()
  229. }
  230. //override func didwake
  231. }
  232. extension EncuestaViewController: ORKTaskViewControllerDelegate {
  233. func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
  234. switch reason {
  235. case .completed:
  236. let taskResult_encuesta = taskViewController.result
  237. //Convertir los resultados a un json
  238. let jsonData = try! ORKESerializer.jsonData(for: taskResult_encuesta)
  239. //Convertir la data del json a un string
  240. jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
  241. jsonString = jsonString.replacingOccurrences(of: "\"isPreviousResult\":false,", with: "")
  242. jsonString = jsonString.replacingOccurrences(of: "\"_class\":\"ORKStepResult\",", with: "")
  243. jsonString = jsonString.replacingOccurrences(of: "\"_class\":\"ORKTaskResult\",", with: "")
  244. jsonString = jsonString.replacingOccurrences(of: "\"_class\":\"ORKTaskResult\",", with: "")
  245. jsonString = jsonString.replacingOccurrences(of: "\"_class\":\"ORKChoiceQuestionResult\",", with: "")
  246. jsonDict = convertToDictionary(text: jsonString as String) as! [String: Any]
  247. let result = limpiarJson()
  248. do {
  249. let jsonData = try JSONSerialization.data(withJSONObject: result, options: .prettyPrinted)
  250. jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
  251. }
  252. catch {
  253. print(error.localizedDescription)
  254. }
  255. sendJson()
  256. case .failed, .discarded, .saved:
  257. break
  258. }
  259. //Handle results with taskViewController.result
  260. taskViewController.dismiss(animated: true, completion: nil)
  261. }
  262. }