Skip to content

Commit f4a6754

Browse files
authored
Merge pull request mouredev#3664 from allbertoMD/Reto-#20
#20-Swift
2 parents a641ea0 + 147361e commit f4a6754

File tree

1 file changed

+180
-0
lines changed

1 file changed

+180
-0
lines changed
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
import Foundation
2+
3+
// ESTE PROGRAMA PARA SU CORRECTRO FUNCIONAMIENTO SIN LOS METODOS sleep() SE TIENE QUE USAR EN UN PLAYGROUND.
4+
5+
var webUrlString = "https://www.swift.org"
6+
guard let webUrl = URL(string: webUrlString) else {
7+
print("URL inválida")
8+
exit(1)
9+
}
10+
11+
// Crear una solicitud URLRequest.
12+
var webRequest = URLRequest(url: webUrl)
13+
webRequest.httpMethod = "GET"
14+
15+
// Crear una sesión URLSession.
16+
let session = URLSession.shared
17+
18+
// Crear una tarea de datos
19+
let task = session.dataTask(with: webRequest) { (data, response, error) in
20+
// Verificar si hay algún error
21+
if let error = error {
22+
print("Error: \(error).")
23+
return
24+
}
25+
26+
// Verificar si se recibió una respuesta HTTP.
27+
guard let httpResponse = response as? HTTPURLResponse else {
28+
print("Respuesta HTTP inválida.")
29+
return
30+
}
31+
32+
// Verificar si la solicitud fue exitosa (código de estado 2xx).
33+
guard (200...299).contains(httpResponse.statusCode) else {
34+
print("Error en la solicitud. Código de estado: \(httpResponse.statusCode).")
35+
return
36+
}
37+
38+
// Verificar si se recibieron datos.
39+
guard let responseData = data else {
40+
print("No se recibieron datos.")
41+
return
42+
}
43+
44+
// Imprime el contenido html de la pagina.
45+
if let dataString = String(data: responseData, encoding: .utf8) {
46+
print(dataString)
47+
} else {
48+
print("No hay datos que mostrar.")
49+
}
50+
}
51+
52+
// Empezar la tarea
53+
task.resume()
54+
sleep(1)
55+
56+
57+
58+
59+
// DIFICULTAD EXTRA
60+
print("\nDIFICULTAD EXTRA.\n")
61+
62+
63+
// Pide por consola el nombre del pokemon para añadirlo al endpoint
64+
print("Introduce el nombre del pokemon que quieras ver la info:")
65+
guard let pokemonName = readLine() else {
66+
fatalError()
67+
}
68+
69+
70+
// Structuras para la info del pokemon
71+
struct Pokemon: Codable {
72+
let gameIndices: [GameIndex]
73+
let height: Int
74+
let id: Int
75+
let name: String
76+
let types: [PokemonType]
77+
let weight: Int
78+
79+
private enum CodingKeys: String, CodingKey {
80+
case gameIndices = "game_indices"
81+
case height, id, name, types, weight
82+
}
83+
}
84+
85+
struct GameIndex: Codable {
86+
let gameIndex: Int
87+
let version: Version
88+
89+
private enum CodingKeys: String, CodingKey {
90+
case gameIndex = "game_index"
91+
case version
92+
}
93+
}
94+
95+
struct Version: Codable {
96+
let name: String
97+
let url: String
98+
}
99+
100+
struct PokemonType: Codable {
101+
let slot: Int
102+
let type: Type
103+
104+
private enum CodingKeys: String, CodingKey {
105+
case slot, type
106+
}
107+
}
108+
109+
struct Type: Codable {
110+
let name: String
111+
let url: String
112+
}
113+
114+
115+
// Solicitud para la info del pokemon
116+
var apiUrlString = "https://pokeapi.co/api/v2/pokemon/\(pokemonName)"
117+
guard var apiUrl = URL(string: apiUrlString) else {
118+
print("URL inválida")
119+
exit(1)
120+
}
121+
122+
// Crear una solicitud URLRequest.
123+
var apiRequest = URLRequest(url: apiUrl)
124+
apiRequest.httpMethod = "GET"
125+
126+
// Crear una sesión URLSession.
127+
let apiSession = URLSession.shared
128+
129+
// Crear una tarea de datos
130+
let apiTask = apiSession.dataTask(with: apiRequest) { (data, response, error) in
131+
// Verificar si hay algún error
132+
if let error = error {
133+
print("Error: \(error).")
134+
return
135+
}
136+
137+
// Verificar si se recibió una respuesta HTTP.
138+
guard let httpResponse = response as? HTTPURLResponse else {
139+
print("Respuesta HTTP inválida.")
140+
return
141+
}
142+
143+
// Verificar si la solicitud fue exitosa (código de estado 2xx).
144+
guard (200...299).contains(httpResponse.statusCode) else {
145+
print("Error en la solicitud. Código de estado: \(httpResponse.statusCode).")
146+
return
147+
}
148+
149+
// Verificar si se recibieron datos.
150+
guard let responseData = data else {
151+
print("No se recibieron datos.")
152+
return
153+
}
154+
155+
let decoder = JSONDecoder()
156+
157+
do {
158+
let pokemon = try decoder.decode(Pokemon.self, from: responseData)
159+
print("Nombre: \(pokemon.name)")
160+
print("ID: \(pokemon.id)")
161+
print("Peso: \(pokemon.weight)")
162+
print("Altura: \(pokemon.height)")
163+
164+
print("Typos: ")
165+
for type in pokemon.types {
166+
print("\t\(type.type.name)")
167+
}
168+
169+
print("Juegos: ")
170+
for game in pokemon.gameIndices {
171+
print("\t\(game.version.name)")
172+
}
173+
} catch {
174+
print(error)
175+
}
176+
}
177+
178+
// Empezar la tarea
179+
apiTask.resume()
180+
sleep(1)

0 commit comments

Comments
 (0)