CalendarViewModel.swift 2.5 KB

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