InstructionViewModel.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // InstructionViewModel.swift
  3. // LMS
  4. //
  5. // Created by Suraj Kumar Mandal on 10/10/23.
  6. //
  7. import Foundation
  8. import Alamofire
  9. class InstructionViewModel {
  10. var quizTime: Int?
  11. func getQuizTime(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.GetQuizTime + "/\(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. guard let text = String(data: jsonData, encoding: .utf8) else {
  37. print("data is not in UTF-8")
  38. return
  39. }
  40. guard let value = Int(text) else {
  41. print("text cannot be converted to Int")
  42. return
  43. }
  44. print(value)
  45. // Once you receive the data from the API
  46. // Parse the data and store it in responseData
  47. self.quizTime = value
  48. // Call the completion handler on the main thread to update the UI
  49. DispatchQueue.main.async {
  50. completion()
  51. }
  52. break
  53. case .failure(let error):
  54. print(error.localizedDescription)
  55. //delegate.showError(error: error.localizedDescription)
  56. break
  57. }
  58. }
  59. }
  60. }
  61. }