How can I make request to an API and then create a view in SwiftUI?

Hello everyone 👋🏻

I’m new to SwiftUI and I’ve been trying with no luck to create a view in SwiftUI with data I’ve get from an API request.

I have defined the structure of the data with Codable, but when I try to JSONDecode(), I can’t access the data from the URLSession.

Can someone help me a little bit? Or tell me where I could find a tutorial that is useful in my case?

Thank you all!
Stay safe!

when I try to JSONDecode(), I can’t access the data from the URLSession.

Please show your code. You may be doing something wrong but no one can find where without seeing your code.
I would recommend using a Combine publisher and then make a class that interfaces with the publisher. You can get a combine publisher from URLSession and then use the built in operators or make some of your own in order to transform the data that you receive to make it easier for SwiftUI to read it. The class that interfaces with the publisher can receive all of its messages and be connected to any SwiftUI view using the @StateObject, @ObservedObject or @EnvironmentObject property wrappers. Make sure that the class interfacing between your publisher and SwiftUI conforms to the ObservableObject protocol (or else it won't work with the aforementioned property wrappers.) I find that the built in operators in Combine work well enough so that creating an operator is usually not required.
2 questions:
  1. Is your JSONDecoder failing? Did you try logging the error?

  2. If so, how are you calling this function in your SwiftUI View?

How can I make request to an API and then create a view in SwiftUI?
 
 
Q