Hello everybody!
I'm having issues loading images from na API. Trying to get a certain image from the PokeAPI. I made a network call, no error, no issues whatsoever but the image is not showing on my ui. Here is the code, take a look and please help me out if you can. Thank you in advace!
class ViewController: UIViewController {
var pokemon: UIImageView = {
let image = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
image.contentMode = .scaleAspectFit
return image
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemTeal
view.addSubview(pokemon)
constraintsPokemon()
getPokemon()
}
func constraintsPokemon() {
pokemon.heightAnchor.constraint(equalToConstant: 100).isActive = true
pokemon.widthAnchor.constraint(equalToConstant: 100).isActive = true
pokemon.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
pokemon.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
func getPokemon() {
guard let url = URL(string: "https://pokeapi.co/api/v2/pokemon/6") else {
print("Wrong URL")
return
}
URLSession.shared.dataTask(with: url) { data, _, error in
if let error = error {
print("AN Error has occured")
}
guard let data = data else {
print("No DATA")
return
}
guard let parsedData = try? JSONDecoder().decode(PokeImage.self, from: data) else {
print("Failed to parse JSON!")
return
}
let pokeImage = parsedData.sprites.other.officialArt.front_default
DispatchQueue.main.async {
self.pokemon.image = UIImage(named: pokeImage)
}
//print(pokeImage)
}.resume()
}
}
struct PokeImage: Codable {
var sprites: Sprites
}
struct Sprites: Codable {
var front_default: String
var other: Other
}
struct Other: Codable {
var officialArt: Front
enum CodingKeys: String, CodingKey {
case officialArt = "official-artwork"
}
}
struct Front: Codable {
var front_default: String
}