Skip to content

Commit c5d9077

Browse files
committed
change post method and add codingkeys
1 parent 308ae0e commit c5d9077

6 files changed

Lines changed: 74 additions & 60 deletions

File tree

AnimalsApp/AnimalsApp.xcodeproj/project.pbxproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
A463D074285A398900929A3C /* HomeViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A463D073285A398900929A3C /* HomeViewModel.swift */; };
3737
A463D078285A5A8000929A3C /* OpenSans-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = A463D077285A5A8000929A3C /* OpenSans-Regular.ttf */; };
3838
A463D07A285B8D8E00929A3C /* Colors.swift in Sources */ = {isa = PBXBuildFile; fileRef = A463D079285B8D8D00929A3C /* Colors.swift */; };
39+
A463D07E285CF28200929A3C /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = A463D07D285CF28200929A3C /* String.swift */; };
3940
/* End PBXBuildFile section */
4041

4142
/* Begin PBXContainerItemProxy section */
@@ -95,6 +96,7 @@
9596
A463D073285A398900929A3C /* HomeViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeViewModel.swift; sourceTree = "<group>"; };
9697
A463D077285A5A8000929A3C /* OpenSans-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "OpenSans-Regular.ttf"; sourceTree = "<group>"; };
9798
A463D079285B8D8D00929A3C /* Colors.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Colors.swift; sourceTree = "<group>"; };
99+
A463D07D285CF28200929A3C /* String.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = String.swift; sourceTree = "<group>"; };
98100
/* End PBXFileReference section */
99101

100102
/* Begin PBXFrameworksBuildPhase section */
@@ -249,6 +251,7 @@
249251
children = (
250252
A463D06128590D0300929A3C /* Images.swift */,
251253
A463D079285B8D8D00929A3C /* Colors.swift */,
254+
A463D07D285CF28200929A3C /* String.swift */,
252255
);
253256
path = DesignSystem;
254257
sourceTree = "<group>";
@@ -571,6 +574,7 @@
571574
5CA996F8285A98FB00FF5D79 /* RegisterViewModel.swift in Sources */,
572575
A463D05D2858F64B00929A3C /* FavoritesViewController.swift in Sources */,
573576
A463D06D285A22D200929A3C /* DetailViewController.swift in Sources */,
577+
A463D07E285CF28200929A3C /* String.swift in Sources */,
574578
A463D069285A1A5A00929A3C /* WebServices.swift in Sources */,
575579
A463D0532858F60C00929A3C /* HomeViewController.swift in Sources */,
576580
);
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
//
2+
// String.swift
3+
// AnimalsApp
4+
//
5+
// Created by Laura Pinheiro Marson on 17/06/22.
6+
//
7+
8+
import Foundation
9+
10+
extension String {
11+
func testIfIsEmpty() -> String? {
12+
if self == "" {
13+
return nil
14+
}
15+
return self
16+
}
17+
}

AnimalsApp/AnimalsApp/Models/Animals.swift

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,26 @@ struct Animals: Codable {
1212
}
1313

1414
struct Animal: Codable {
15-
let id: String
16-
let name: String?
17-
let description: String?
18-
let age: Int?
19-
let species: String?
20-
let image: String?
21-
let created_at: String
22-
var updated_at: String
15+
var id: String?
16+
var name: String?
17+
var description: String?
18+
var age: Int?
19+
var species: String?
20+
var image: String?
21+
var createdAt: String?
22+
var updatedAt: String?
2323
var isFavorite: Bool? = false
24+
25+
enum CodingKeys: String, CodingKey {
26+
case id
27+
case name
28+
case description
29+
case age
30+
case species
31+
case image
32+
case createdAt = "created_at"
33+
case updatedAt = "updated_at"
34+
}
2435
}
2536

2637
extension Animal {

AnimalsApp/AnimalsApp/Services/WebServices.swift

Lines changed: 13 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import Alamofire
1111
protocol WebServicesContract: AnyObject {
1212
var endpoint: String { get }
1313
func fetchAnimals(completion: @escaping (Result<[Animal], Error>) -> ())
14-
func registerAnimal(with parameters: [String: Any], handler: @escaping (() -> Void))
14+
func registerAnimal(with parameters: Animal, completion: @escaping (Result<Void, Error>) -> Void)
1515
}
1616

1717
class WebServices: WebServicesContract {
@@ -31,34 +31,18 @@ class WebServices: WebServicesContract {
3131
}
3232
}
3333

34-
func registerAnimal(with parameters: [String: Any], handler: @escaping (() -> Void)) {
35-
AF.request(endpoint, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).validate(statusCode: 200 ..< 299).responseData { response in
36-
switch response.result {
37-
case .success(let data):
38-
handler()
39-
do {
40-
guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
41-
print("Error: Cannot convert data to JSON object")
42-
return
43-
}
44-
guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
45-
print("Error: Cannot convert JSON object to Pretty JSON data")
46-
return
47-
}
48-
guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
49-
print("Error: Could print JSON in String")
50-
return
51-
}
52-
53-
print(prettyPrintedJson)
54-
} catch {
55-
print("Error: Trying to convert JSON data to string")
56-
return
57-
}
58-
case .failure(let error):
59-
handler()
60-
print(error)
61-
}
34+
func registerAnimal(with parameters: Animal, completion: @escaping (Result<Void, Error>) -> Void) {
35+
36+
AF.request(endpoint,
37+
method: .post,
38+
parameters: parameters,
39+
encoder: JSONParameterEncoder.default).response { response in
40+
switch response.result {
41+
case .success:
42+
completion(.success(()))
43+
case .failure(let error):
44+
completion(.failure(error))
6245
}
46+
}
6347
}
6448
}

AnimalsApp/AnimalsApp/View Models/RegisterViewModel.swift

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,19 @@ struct RegisterViewModel {
1414
self.webServices = webServices
1515
}
1616

17-
func registerAnimal(with parameters: [String: Any], handler: @escaping (() -> Void)) {
18-
webServices.registerAnimal(with: parameters) {
19-
handler()
17+
func registerAnimal(name: String, description: String, age: Int, species: String, image: String, completion: @escaping (() -> Void)) {
18+
19+
let newAnimal = Animal(name: name, description: description, age: age, species: species, image: image)
20+
21+
webServices.registerAnimal(with: newAnimal) { (result) in
22+
switch result {
23+
case .success:
24+
completion()
25+
case .failure(let error):
26+
//obs criar alerta
27+
print(error.localizedDescription)
28+
completion()
29+
}
2030
}
2131
}
2232
}

AnimalsApp/AnimalsApp/Views/RegisterViewController/RegisterViewController.swift

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,6 @@ import Alamofire
1111
class RegisterViewController: UIViewController {
1212
// MARK: Properties
1313
var registerVM = RegisterViewModel()
14-
var parameters: [String: Any] = [
15-
"name": "",
16-
"description": "",
17-
"age": 0,
18-
"specie": "",
19-
"image": ""
20-
]
2114

2215
// MARK: Outlets
2316
@IBOutlet weak var textFieldName: UITextField!
@@ -39,13 +32,16 @@ class RegisterViewController: UIViewController {
3932

4033
// MARK: Actions
4134
@IBAction func handlerButtonRegister(_ sender: Any) {
42-
if textFieldName.text == "" || textFieldImageLink.text == "" || textFieldDescription.text == "" || textFieldSpecie.text == "" || textFieldAge.text == "" {
35+
guard let name = textFieldName.text?.testIfIsEmpty(),
36+
let description = textFieldDescription.text?.testIfIsEmpty(),
37+
let age = Int(textFieldAge.text ?? ""),
38+
let species = textFieldSpecie.text?.testIfIsEmpty(),
39+
let image = textFieldImageLink.text?.testIfIsEmpty() else {
4340
showAlerts(alertTitle: "Erro", alertMessage: "Preencha todos os dados")
44-
return
45-
}
41+
return }
42+
4643
activityIndicator.startAnimating()
47-
setParameters()
48-
registerVM.registerAnimal(with: parameters) {
44+
registerVM.registerAnimal(name: name, description: description, age: age, species: species, image: image) {
4945
self.activityIndicator.stopAnimating()
5046
}
5147
}
@@ -80,14 +76,6 @@ class RegisterViewController: UIViewController {
8076
buttonRegister.layer.cornerRadius = 10
8177
}
8278

83-
private func setParameters() {
84-
parameters["name"] = textFieldName.text
85-
parameters["description"] = textFieldDescription.text
86-
parameters["age"] = Int(textFieldAge.text ?? "0")
87-
parameters["specie"] = textFieldSpecie.text
88-
parameters["image"] = textFieldImageLink.text
89-
}
90-
9179
private func delegateTextField() {
9280
textFieldAge.delegate = self
9381
textFieldName.delegate = self

0 commit comments

Comments
 (0)