StudyMaterialsViewModel.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // StudyMaterialsViewModel.swift
  3. // LMS
  4. //
  5. // Created by Suraj Kumar Mandal on 06/09/22.
  6. //
  7. import Foundation
  8. import Alamofire
  9. class StudyMaterialsViewModel {
  10. var delegate: StudyMaterialsProtocol?
  11. func getUnitsList(userId:Int) {
  12. if let delegate = delegate {
  13. delegate.startLoader()
  14. let accessToken = UserDefaults.standard.value(forKey: "accessToken") as! String
  15. let url = ApiURL.GetUnitsList + "/\(userId)/false"
  16. print(url)
  17. let headers: HTTPHeaders = [
  18. "Authorization": "Bearer \(accessToken)",
  19. "Accept": "application/json",
  20. "Content-Type": "application/json"
  21. ]
  22. print(headers)
  23. AF.request(url,
  24. method: .get,
  25. encoding: URLEncoding.httpBody,
  26. headers: headers)
  27. .responseJSON { response in
  28. if response.response?.statusCode == 200 {
  29. switch response.result {
  30. case .success(_):
  31. delegate.stopLoader()
  32. guard let jsonData = response.data else {
  33. return
  34. }
  35. let decoder = JSONDecoder()
  36. do {
  37. let unitsData = try decoder.decode([UnitsListModel].self, from: jsonData)
  38. delegate.unitsModel(model: unitsData)
  39. print(unitsData.count)
  40. } catch {
  41. print("getDataList Unexpected error: \(error).")
  42. delegate.showError(error: "getDataList Unexpected error: \(error).")
  43. }
  44. break
  45. case .failure(let error):
  46. delegate.stopLoader()
  47. print(error.localizedDescription)
  48. delegate.showError(error: error.localizedDescription)
  49. break
  50. }
  51. }
  52. }
  53. }
  54. }
  55. }
  56. protocol StudyMaterialsProtocol {
  57. func startLoader()
  58. func stopLoader()
  59. func showError(error:String)
  60. func unitsModel(model: [UnitsListModel])
  61. }