ViewAnswersViewModel.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // ViewAnswersViewModel.swift
  3. // LMS
  4. //
  5. // Created by Suraj Kumar Mandal on 20/10/23.
  6. //
  7. import Foundation
  8. import Alamofire
  9. class ViewAnswersViewModel {
  10. var answersModel = [AssessmentResultModel]()
  11. func getSubmittedAnswers(userId:Int, sessionId:String, assessmentId:Int, completion: @escaping () -> Void) {
  12. // Perform the API request in the background thread
  13. DispatchQueue.global().async {
  14. // Make your API call here
  15. // You can use URLSession or any networking library of your choice
  16. let accessToken = UserDefaults.standard.value(forKey: "accessToken") as! String
  17. let url = ApiURL.GeAllSubmittedAnswers + "/\(userId)" + "/\(sessionId)" + "/\(assessmentId)"
  18. print(url)
  19. let headers: HTTPHeaders = [
  20. "Authorization": "Bearer \(accessToken)",
  21. "Accept": "application/json",
  22. "Content-Type": "application/json"
  23. ]
  24. print(headers)
  25. AF.request(url,
  26. method: .get,
  27. encoding: URLEncoding.httpBody,
  28. headers: headers)
  29. .responseString { response in
  30. switch response.result {
  31. case .success(_):
  32. guard let jsonData = response.data else {
  33. return
  34. }
  35. print(jsonData)
  36. // Once you receive the data from the API
  37. // Parse the data and store it in responseData
  38. let assessmentResultModel = try? JSONDecoder().decode([AssessmentResultModel].self, from: jsonData)
  39. self.answersModel = assessmentResultModel ?? []
  40. // Call the completion handler on the main thread to update the UI
  41. DispatchQueue.main.async {
  42. completion()
  43. }
  44. break
  45. case .failure(let error):
  46. print(error.localizedDescription)
  47. //delegate.showError(error: error.localizedDescription)
  48. break
  49. }
  50. }
  51. }
  52. }
  53. }