No Description

NetworkingModel.swift 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. //
  2. // DataModel.swift
  3. // Comedores Sociales
  4. //
  5. // Created by Hector Carrion on 11/8/20.
  6. //
  7. import Foundation
  8. let serverAddress: String = "http://161.35.60.201/"
  9. class Authentication: Codable {
  10. var correo: String
  11. var password: String
  12. init(email: String, password: String) {
  13. self.correo = email
  14. self.password = password
  15. }
  16. func isComplete() -> Bool {
  17. if correo != "" && password != "" {
  18. return true
  19. } else {
  20. return false
  21. }
  22. }
  23. }
  24. class Registration: Codable {
  25. var username: String
  26. var password: String
  27. var nombre: String
  28. var urbanizacion: String
  29. var calle: String
  30. var pueblo: String
  31. var cpostal: String
  32. var telefono: String
  33. var correo: String
  34. var organizacion: String?
  35. var puesto: String?
  36. init(email: String, password: String, name: String, urb: String, street: String, city: String, zip: String, phone: String, org: String? = nil, position: String? = nil) {
  37. if org != "" {
  38. self.username = email
  39. self.password = password
  40. self.nombre = name
  41. self.urbanizacion = urb
  42. self.calle = street
  43. self.pueblo = city
  44. self.cpostal = zip
  45. self.telefono = phone
  46. self.correo = email
  47. self.organizacion = org
  48. self.puesto = position
  49. } else {
  50. self.username = email
  51. self.password = password
  52. self.nombre = name
  53. self.urbanizacion = urb
  54. self.calle = street
  55. self.pueblo = city
  56. self.cpostal = zip
  57. self.telefono = phone
  58. self.correo = email
  59. self.organizacion = nil
  60. self.puesto = nil
  61. }
  62. }
  63. func isComplete() -> Bool {
  64. if username != "" && password != "" && nombre != "" && urbanizacion != "" && calle != "" && pueblo != "" && cpostal != "" && telefono != "" && correo != "" {
  65. return true
  66. } else {
  67. return false
  68. }
  69. }
  70. }
  71. enum Response {
  72. case success
  73. case failure
  74. case loading
  75. case unfetched
  76. }
  77. struct UserToken: Codable {
  78. let token: String
  79. }
  80. func getToken(input: String) -> UserToken {
  81. let JSONData = input.data(using: .utf8)!
  82. let token: UserToken = try! JSONDecoder().decode(UserToken.self, from: JSONData)
  83. return token
  84. }
  85. struct UserDetails: Codable {
  86. let correo: String
  87. let nombre: String
  88. let organizacion: String?
  89. let puesto: String?
  90. let calle: String
  91. let pueblo: String
  92. let cpostal: String
  93. let telefono: String
  94. let membresia: String?
  95. let vigencia: String?
  96. let horas_trabajadas: String?
  97. }
  98. func getUserDetails(input: String) -> UserDetails {
  99. let JSONData = input.data(using: .utf8)!
  100. let info: UserDetails = try! JSONDecoder().decode(UserDetails.self, from: JSONData)
  101. return info
  102. }
  103. class LoginViewModel: ObservableObject {
  104. @Published var response: Response = .unfetched
  105. func changeResponse(response: Bool) {
  106. if response == true {
  107. self.response = .success
  108. } else {
  109. self.response = .failure
  110. }
  111. }
  112. func login(data: Authentication) {
  113. self.response = .loading
  114. let service = "api/login.php"
  115. guard let encodedData = try? JSONEncoder().encode(data)
  116. else {
  117. print("Failed to encode login request")
  118. return
  119. }
  120. //print("JSON to send:", String(data: encodedData, encoding: .utf8)!)
  121. let url = URL(string: serverAddress + service)!
  122. var request = URLRequest(url: url)
  123. request.setValue("applogin/json", forHTTPHeaderField: "Content-Type")
  124. request.httpMethod = "POST"
  125. request.httpBody = encodedData
  126. URLSession.shared.dataTask(with: request) {data, response, error in
  127. //handle result here
  128. guard let data = data
  129. else {
  130. print("No data in response: \(error?.localizedDescription ?? "Unknown error").")
  131. return
  132. }
  133. print(response ?? "No response")
  134. print("Recieved data:", data)
  135. print(error ?? "No error")
  136. if let httpResponse = response as? HTTPURLResponse {
  137. DispatchQueue.main.async {
  138. if httpResponse.statusCode == 200 {
  139. self.changeResponse(response: true)
  140. // MARK: JSON Decoding
  141. let dataString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
  142. let json = getToken(input: dataString)
  143. let defaults = UserDefaults.standard
  144. defaults.set(json.token, forKey: "token")
  145. defaults.set(true, forKey: "logged-in")
  146. } else {
  147. self.changeResponse(response: false)
  148. }
  149. }
  150. }
  151. }.resume()
  152. }
  153. }
  154. class RegisterViewModel: ObservableObject {
  155. @Published var response: Response = .unfetched
  156. func changeResponse(response: Bool) {
  157. if response == true {
  158. self.response = .success
  159. } else {
  160. self.response = .failure
  161. }
  162. }
  163. func register(data: Registration) {
  164. self.response = .loading
  165. let service = "signup.php"
  166. guard let encodedData = try? JSONEncoder().encode(data)
  167. else {
  168. print("Failed to encode register request")
  169. return
  170. }
  171. //print("Reg JSON to send:", String(data: encodedData, encoding: .utf8)!)
  172. let url = URL(string: serverAddress + service)!
  173. var request = URLRequest(url: url)
  174. request.setValue("appregister/json", forHTTPHeaderField: "Content-Type")
  175. request.httpMethod = "POST"
  176. request.httpBody = encodedData
  177. URLSession.shared.dataTask(with: request) {data, response, error in
  178. //handle result here
  179. guard let data = data
  180. else {
  181. print("No data in response: \(error?.localizedDescription ?? "Unknown error").")
  182. return
  183. }
  184. print(response ?? "No response")
  185. print("Recieved data:", data)
  186. print(error ?? "No error")
  187. if let httpResponse = response as? HTTPURLResponse {
  188. DispatchQueue.main.async {
  189. if httpResponse.statusCode == 200 {
  190. self.changeResponse(response: true)
  191. } else {
  192. self.changeResponse(response: false)
  193. }
  194. }
  195. }
  196. }.resume()
  197. }
  198. }
  199. class ProfileViewModel: ObservableObject {
  200. @Published var profile: Profile = .default
  201. @Published var response: Response = .unfetched
  202. func changeResponse(response: Bool) {
  203. if response == true {
  204. self.response = .success
  205. } else {
  206. self.response = .failure
  207. }
  208. }
  209. func changeProfile(data: UserDetails) {
  210. self.profile.name = data.nombre
  211. self.profile.email = data.correo
  212. self.profile.phone = addDashes(phone: data.telefono)
  213. if data.membresia != "" {
  214. self.profile.membership = data.membresia ?? "No memebership recieved from server"
  215. }
  216. if (data.vigencia != nil) {
  217. self.profile.membershipStatus = .valid
  218. } else {
  219. self.profile.membershipStatus = .expired
  220. }
  221. if let hours = data.horas_trabajadas {
  222. self.profile.hoursWorked = Int(hours) ?? 0
  223. }
  224. }
  225. func fetchMember(token: UserToken) {
  226. self.response = .loading
  227. let service = "api/member.php"
  228. guard let encodedData = try? JSONEncoder().encode(token)
  229. else {
  230. print("Failed to encode login request")
  231. return
  232. }
  233. //print("JSON to send:", String(data: encodedData, encoding: .utf8)!)
  234. let url = URL(string: serverAddress + service)!
  235. var request = URLRequest(url: url)
  236. request.setValue("appmember/json", forHTTPHeaderField: "Content-Type")
  237. request.httpMethod = "POST"
  238. request.httpBody = encodedData
  239. URLSession.shared.dataTask(with: request) {data, response, error in
  240. //handle result here
  241. guard let data = data
  242. else {
  243. print("No data in response: \(error?.localizedDescription ?? "Unknown error").")
  244. return
  245. }
  246. print(response ?? "No response")
  247. print("Recieved data:", data)
  248. print(error ?? "No error")
  249. if let httpResponse = response as? HTTPURLResponse {
  250. DispatchQueue.main.async {
  251. if httpResponse.statusCode == 200 {
  252. // MARK: JSON Decoding
  253. let dataString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
  254. let json = getUserDetails(input: dataString)
  255. //print(json)
  256. self.changeResponse(response: true)
  257. self.changeProfile(data: json)
  258. } else {
  259. self.changeResponse(response: false)
  260. }
  261. }
  262. }
  263. }.resume()
  264. }
  265. }
  266. func addDashes(phone: String) -> String {
  267. var prettyPhone: String = ""
  268. var i = 0
  269. for number in phone {
  270. prettyPhone.append(number)
  271. if i == 2 || i == 5 {
  272. prettyPhone.append("-")
  273. }
  274. i += 1
  275. }
  276. return prettyPhone
  277. }