Brak opisu

EncuestaViewController.swift 12KB

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