NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: Error consuming API

Forums > SwiftUI

Now im trynt to consume via API...


    func buscaAPI() {
        // fetch json, decode, e update property array
        guard let url = URL(string: apiUrl) else { return }
        URLSession.shared.dataTask(with: url) { (data, resp, err) in
            // check error

            DispatchQueue.main.sync {
                self.listagemProdutos = try! JSONDecoder().decode([Produtos].self, from: data!)

struct Produtos : Identifiable, Decodable{
    var id = UUID()
    var produto : String
    var descricao : String
    var imagem : String
    var preco : Double
    var destaque : Bool
    var categoria : String
    var ordenacao : Int

    enum CodingKeys: String, CodingKey {
        case produto, descricao, imagem, preco, destaque, categoria, ordenacao


but data dont appers....


please help me, no data shows in I acess via api, but when local its work normal.


So there are two things you can do here to debug. The first is to print out the error you are probably receiving in the closure ( where you say // check error). Print everything you get out, data, resp, and error.

The other is to just run the debugger.

Paul rarely shows the debugger but that I think i because he needs to build and run code in a short time.

Looking at that code though it looks like it would in fact crash on missing data, is that what you are seeing?


Actually its possible that your apiURLStr is missing, it is good practice to pass in those values into the method rather than depend on an instance variable.


My friend, the problem was the view, no error was showed. (sorry my english kkk).

I changed:

var vModel : ProdutosVM 
@StateObject var vModel : ProdutosVM

and boom, its work perfectly... but this bug ocurr only when i fetch data from json file in internet, if i consum in local archive it was working fine..

sinceraly i dont understend when my call for obserserv object dont work i need to use @stateobject???, but i i dont understend what is happing, why somethings the view dont update?.....

but with this change the code works fine!


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try 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.