暫無描述

HistoryService.swift 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // HistoryService.swift
  3. // Flowerdex
  4. //
  5. // Created by Víctor A. Hernández on 12/21/20.
  6. //
  7. import Foundation
  8. class HistoryService: ObservableObject {
  9. @Published var response: Response = .unfetched
  10. @Published var items = [FlowerVerbose]()
  11. private func getBaseURLComponent(_ apiPath: String) -> URLComponents {
  12. var components = URLComponents()
  13. components.scheme = Constants.Services.apiScheme
  14. components.host = Constants.Services.apiHost
  15. components.path = apiPath
  16. if apiPath == Constants.Services.apiGetHistoryPath {
  17. components.queryItems = [
  18. URLQueryItem(name: "user_id", value: "\(User.current.id!)"),
  19. ]
  20. }
  21. return components
  22. }
  23. private func fetchFlowers(_ request: URLRequest) {
  24. URLSession.shared.dataTask(with: request) { data, response, error in
  25. guard let data = data else {
  26. print("No data in response: \(error?.localizedDescription ?? "Unknown error")")
  27. DispatchQueue.main.async {
  28. self.response = .failure
  29. }
  30. return
  31. }
  32. print(response ?? "No response")
  33. // print("Recieved data:", String(decoding: data, as: UTF8.self))
  34. guard let apiResponse = try? JSONDecoder().decode(HistoryResponseModel.self, from: data) else {
  35. print("Failed to decode History response")
  36. DispatchQueue.main.async {
  37. self.response = .failure
  38. }
  39. return
  40. }
  41. if let httpResponse = response as? HTTPURLResponse {
  42. DispatchQueue.main.async {
  43. if httpResponse.statusCode == 200 && apiResponse.error == nil {
  44. print("No error")
  45. self.response = .success
  46. self.items = apiResponse.data!
  47. } else {
  48. print("Error: \(apiResponse.error ?? "Unknown error")")
  49. self.response = .failure
  50. // self.items = [FlowerVerbose]()
  51. }
  52. }
  53. }
  54. }.resume()
  55. }
  56. func getHistory() {
  57. // Start loading state
  58. self.response = .loading
  59. // Construct URL
  60. let components = getBaseURLComponent(Constants.Services.apiGetHistoryPath)
  61. // Prepare and carry out request
  62. var request = URLRequest(url: components.url!)
  63. request.httpMethod = "GET"
  64. self.fetchFlowers(request)
  65. }
  66. func getWishlist() {
  67. // Start loading state
  68. self.response = .loading
  69. // Construct URL
  70. let components = getBaseURLComponent(Constants.Services.apiGetWishlistPath)
  71. // Prepare and carry out request
  72. var request = URLRequest(url: components.url!)
  73. request.httpMethod = "GET"
  74. self.fetchFlowers(request)
  75. }
  76. }