I'm learning swift and I wanted to pull some data from a django model to work with, so I was following a tutorial on YouTube. I copied the code on YouTube and I got his Breaking Bad API (https://breakingbadapi.com/api/quotes) to display on my simulator, however when I subbed in the URL to my API, I returned an empty list and my simulator displays only a blank screen. I've tried using both http://127.0.0.1:8000/api/main_course/ and http://127.0.0.1:8000/api/main_course/?format=json
From my terminal I get 200 OK: [14/Sep/2022 21:28:48] "GET /api/main_course/ HTTP/1.1" 200 1185
Here's my code:
import SwiftUI
struct Entree: Codable {
var id: Int
var menu: String
var name: String
var descripton: String
}
struct ContentView: View {
@State private var entrees = [Entree]()
var body: some View {
List(entrees, id: \.id) {entree in
Text(entree.name)
Text("Run")
}
.task {
await loadData()
print(entrees)
}
}
func loadData() async {
// create URL
guard let url = URL(string: "http://127.0.0.1:8000/api/main_course/") else {
print("URL Invalid")
return
}
// fetch data from that URL
do {
let (data, _) = try await URLSession.shared.data(from: url)
// decode that data
if let decodedResponse = try? JSONDecoder().decode([Entree].self, from: data) {
entrees = decodedResponse
}
}
catch {
print("Data invalid")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
CodePudding user response:
It seems that it is on the conversion. Try using the same keys.
struct Entree: Codable {
var quoteId: Int
var quote: String
var author: String
var series: String
enum CodingKeys: String, CodingKey {
case quoteId = "quote_id"
}
}