123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280 |
- //
- // EncuestaViewController.swift
- // Encuesta_MARLE
- //
- // Created by Tatiana Castro on 1/31/19.
- // Copyright © 2019 Tatiana Castro. All rights reserved.
- //
- import UIKit
- import ResearchKit
-
- //let semaphore = DispatchSemaphore(value: -1)
-
- var token = String()
- let URL = "http://emaapp.online/getSubQ2.php?tk="+token;
- var preguntas = [String]()
- var descripcion = String()
- var id_preg = [String]()
- var tipo_preg = [String]()
- var cantidad_preguntas = Int()
- var max_values = [String]()
- var max_text = [String]()
- var min_text = [String]()
- var id_questionario = String()
- var jsonString = String()
- var jsonDict = [String: Any]()
- var n_jsonDict = [String: Any]()
- var response_survey = String()
-
- func getJsonFromUrl(){
- print("entre a getJsonFromUrl")
- let request = NSMutableURLRequest(url: NSURL(string: "http://emaapp.online/getSubQ2.php?tk="+token)! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60)
- // let request = NSMutableURLRequest(url: NSURL(string: "http://emaapp.online/getSubQ2.php?tk="+token)! as URL)
- request.httpMethod = "POST"
- let postString = "data=\(jsonString_reg)"
- request.httpBody = postString.data(using: String.Encoding.utf8)
-
- let task = URLSession.shared.dataTask(with: request as URLRequest) {
- data, response, error in
- if error != nil {
- print("error=\(String(describing: error))")
- return
- }
- let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
- if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
- if let id = jsonObj!.value(forKey: "id_subquestionnair") as? String {
- id_questionario = id
- }
- if let des = jsonObj!.value(forKey: "description") as? String {
- descripcion = des
- }
- if let cantidad = jsonObj!.value(forKey: "cantidad_preguntas") as? String {
- cantidad_preguntas = Int(cantidad) ?? 0
- }
- if let jsonArray = jsonObj!.value(forKey: "preguntas") as? NSArray {
- for subj in jsonArray{
- if let subjDict = subj as? NSDictionary {
- if let pregunta = subjDict.value(forKey: "premise") {
- preguntas.append((pregunta as? String)!)
- }
- }
- if let subjDict = subj as? NSDictionary {
- if let id = subjDict.value(forKey: "id_question") {
- id_preg.append((id as? String)!)
- }
- }
- if let subjDict = subj as? NSDictionary {
- if let tipo = subjDict.value(forKey: "id_type") {
- tipo_preg.append((tipo as? String)!)
- }
- }
- if let subjDict = subj as? NSDictionary {
- if let val = subjDict.value(forKey: "max_val") {
- max_values.append((val as? String)!)
- }
- }
- if let subjDict = subj as? NSDictionary {
- if let mx_txt = subjDict.value(forKey: "max_text") {
- max_text.append((mx_txt as? String)!)
- }
- }
- if let subjDict = subj as? NSDictionary {
- if let mn_txt = subjDict.value(forKey: "min_text") {
- min_text.append((mn_txt as? String)!)
- }
- }
- }
- }
- }
-
-
-
- print("response solito = \(String(describing: response))") //Error: 1062
-
- print("responseString reg= \(String(describing: responseString))")
- //if(responseString)
- response_survey = responseString! as String
- }
- task.resume()
-
- // let url = NSURL(string: URL)
- // URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
- // if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
- // print("entre a jsonObj")
- // print(jsonObj as Any)
- // if let id = jsonObj!.value(forKey: "id_subquestionnair") as? String {
- // id_questionario = id
- // }
- // if let des = jsonObj!.value(forKey: "description") as? String {
- // descripcion = des
- // }
- // if let cantidad = jsonObj!.value(forKey: "cantidad_preguntas") as? String {
- // cantidad_preguntas = Int(cantidad) ?? 0
- // }
- // if let jsonArray = jsonObj!.value(forKey: "preguntas") as? NSArray {
- // for subj in jsonArray{
- // if let subjDict = subj as? NSDictionary {
- // if let pregunta = subjDict.value(forKey: "premise") {
- // preguntas.append((pregunta as? String)!)
- // }
- // }
- // if let subjDict = subj as? NSDictionary {
- // if let id = subjDict.value(forKey: "id_question") {
- // id_preg.append((id as? String)!)
- // }
- // }
- // if let subjDict = subj as? NSDictionary {
- // if let tipo = subjDict.value(forKey: "id_type") {
- // tipo_preg.append((tipo as? String)!)
- // }
- // }
- // if let subjDict = subj as? NSDictionary {
- // if let val = subjDict.value(forKey: "max_val") {
- // max_values.append((val as? String)!)
- // }
- // }
- // if let subjDict = subj as? NSDictionary {
- // if let mx_txt = subjDict.value(forKey: "max_text") {
- // max_text.append((mx_txt as? String)!)
- // }
- // }
- // if let subjDict = subj as? NSDictionary {
- // if let mn_txt = subjDict.value(forKey: "min_text") {
- // min_text.append((mn_txt as? String)!)
- // }
- // }
- // }
- // }
- // if error != nil {
- // print("error=\(String(describing: error))")
- // return
- // }
- // print("response = \(String(describing: response))")
- // let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
- // print("responseString = \(String(describing: responseString))")
- // response_survey = responseString! as String
- // }
- // }).resume()
- // semaphore.signal()
- //semaphore.wait(semaphore,)
- // dispatch_semaphore_wait(semaphore,dispatch_time_t(DispatchTime.distantFuture))
- }
-
- func sendJson(){
-
- let request = NSMutableURLRequest(url: NSURL(string: "http://emaapp.online/parseAnswers2.php")! as URL)
- request.httpMethod = "POST"
- let postString = "data=\(jsonString)"
- request.httpBody = postString.data(using: String.Encoding.utf8)
-
- let task = URLSession.shared.dataTask(with: request as URLRequest) {
- data, response, error in
-
- if error != nil {
- print("error=\(String(describing: error))")
- return
- }
-
- print("response = \(String(describing: response))")
-
- let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
- print("responseString = \(String(describing: responseString))")
- }
- task.resume()
- }
-
- func convertToDictionary(text: String) -> [String: Any]? {
- if let data = text.data(using: .utf8) {
- do {
- return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
- } catch {
- print(error.localizedDescription)
- }
- }
- return nil
- }
-
- func limpiarJson()->Dictionary<String, Any>{
- var data = [String:Any]()
- n_jsonDict["token"]=String(token)
- n_jsonDict["os"]="ios"
- let resultados_encuestas = jsonDict["results"] as! [[String:Any]]
- for i in 0..<cantidad_preguntas{
- if let resultado_pregunta = resultados_encuestas[i]["results"] as? [[String:Any]],
- var resultado = resultado_pregunta.first {
- data["startDate"] = resultado["startDate"]
- data["identifier"] = resultado["identifier"]
- data["questionType"] = resultado["questionType"]
- data["choiceAnswers"] = resultado["choiceAnswers"]
- data["endDate"] = resultado["endDate"]
- }
- n_jsonDict["pregunta"+String(i+1)+"resultados"] = data
- }
- n_jsonDict["id_subquestionnair"]=jsonDict["identifier"]
-
- return n_jsonDict
- }
-
- class EncuestaViewController: UIViewController {
- @IBAction func tomar_encuesta(_ sender: UIButton) {
- //getJsonFromUrl()
- //semaphore.wait()
- if response_survey == "Error:NoHay"{
- let alertTitle = NSLocalizedString("No Survey", comment: "")
- let alertMessage = NSLocalizedString("There is no survey available right now. Please check later.", comment: "")
- let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
- alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
- self.present(alert, animated: true, completion: nil)
- }
- else{
- let taskViewController = ORKTaskViewController(task: EncuestaMarle, taskRun: nil)
- taskViewController.delegate = (self as ORKTaskViewControllerDelegate)
- present(taskViewController, animated: true, completion: nil)
- //print("voy a llamar getJsonFromUrl desde controller")
- //getJsonFromUrl()
- }
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
- print("voy a llamar getJsonFromUrl")
- getJsonFromUrl()
- //semaphore.signal()
-
- }
-
- //override func didwake
- }
-
- extension EncuestaViewController: ORKTaskViewControllerDelegate {
- func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
- switch reason {
- case .completed:
- let taskResult_encuesta = taskViewController.result
-
- //Convertir los resultados a un json
- let jsonData = try! ORKESerializer.jsonData(for: taskResult_encuesta)
- //Convertir la data del json a un string
- jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
- jsonString = jsonString.replacingOccurrences(of: "\"isPreviousResult\":false,", with: "")
- jsonString = jsonString.replacingOccurrences(of: "\"_class\":\"ORKStepResult\",", with: "")
- jsonString = jsonString.replacingOccurrences(of: "\"_class\":\"ORKTaskResult\",", with: "")
- jsonString = jsonString.replacingOccurrences(of: "\"_class\":\"ORKTaskResult\",", with: "")
- jsonString = jsonString.replacingOccurrences(of: "\"_class\":\"ORKChoiceQuestionResult\",", with: "")
- jsonDict = convertToDictionary(text: jsonString as String) as! [String: Any]
- let result = limpiarJson()
- do {
- let jsonData = try JSONSerialization.data(withJSONObject: result, options: .prettyPrinted)
- jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
- }
- catch {
- print(error.localizedDescription)
- }
- sendJson()
- case .failed, .discarded, .saved:
- break
- }
- //Handle results with taskViewController.result
- taskViewController.dismiss(animated: true, completion: nil)
- }
- }
|