Hello everyone, I'm new to SwiftUI and I have a problem: I can't display a list of data from the (https://www.thecocktaildb.com/api.php)
Here is the code :
//
// ContentView.swift
// CocktailsApp
//
// Created by Maxence Svensson on 19/08/2021.
//
import SwiftUI
struct Response: Codable {
var drinks: [********]
}
struct ********: Codable {
var idDrink: Int
var strDrink: String
var strInstructions: String
}
struct ContentView: View {
@State var results = [********]()
var body: some View {
List(results, id: \.idDrink) { item in
VStack(alignment: .leading) {
Text(item.strDrink)
.font(.headline)
Text(item.strInstructions)
}
}
.onAppear(perform: loadData)
}
func loadData(){
guard let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data,response, error in
if let data = data {
if let decodeResponse = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
self.results = decodeResponse.drinks
}
return
}
}
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Thank you in advance for your solutions