UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Images not loading from an API call

Forums > Swift

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 }

2      

UIImage(named: pokeImage)

UIImage's init(named:) method loads an image from your assets. But you want to load this pokemon image from a URL found in the JSON response.

You need to get the image URL from the JSON, get the data from the URL, use UIImage(data: data) to create the image, and then assign it to self.pokemon.image.

2      

I got it now, thanks for pointing this out, things are loading now as they should. Tnx again!

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.