LessonListViewModel.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // LessonListViewModel.swift
  3. // LMS
  4. //
  5. // Created by Suraj Kumar Mandal on 06/09/22.
  6. //
  7. import Foundation
  8. import Alamofire
  9. class LessonListViewModel {
  10. var delegate: LessonListProtocol?
  11. func getLessonsList(id:Int) {
  12. if let delegate = delegate {
  13. delegate.startLoader()
  14. let accessToken = UserDefaults.standard.value(forKey: "accessToken") as! String
  15. let url = ApiURL.GetLessonsList
  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. let parameters: [String: Int] = [
  24. "lessonId" : id
  25. ]
  26. print(parameters)
  27. AF.request(url,
  28. method: .post,
  29. parameters: parameters,
  30. encoding: JSONEncoding.default,
  31. headers: headers)
  32. .responseJSON { response in
  33. if response.response?.statusCode == 200 {
  34. switch response.result {
  35. case .success(_):
  36. delegate.stopLoader()
  37. guard let jsonData = response.data else {
  38. return
  39. }
  40. let decoder = JSONDecoder()
  41. do {
  42. let lessonListData = try decoder.decode([LessonListModel].self, from: jsonData)
  43. delegate.lessonListModel(model: lessonListData)
  44. print(lessonListData.count)
  45. } catch {
  46. print("getDataList Unexpected error: \(error).")
  47. delegate.showError(error: "getDataList Unexpected error: \(error).")
  48. }
  49. break
  50. case .failure(let error):
  51. delegate.stopLoader()
  52. print(error.localizedDescription)
  53. delegate.showError(error: error.localizedDescription)
  54. break
  55. }
  56. } else {
  57. delegate.stopLoader()
  58. print("Server error")
  59. }
  60. }
  61. }
  62. }
  63. }
  64. protocol LessonListProtocol {
  65. func startLoader()
  66. func stopLoader()
  67. func showError(error:String)
  68. func lessonListModel(model: [LessonListModel])
  69. }