这是 SWIFTUI 代码的代码,它使用 JSON 数据解析并显示 API。
//
// trivia.swift
// hw4
//
// Created by somebody else on 4/15/24.
//
//
import SwiftUI
struct Trivia: Identifiable, Decodable {
let id = UUID()
var type: String
var difficulty: String
var category: String
var question: String
var correct: String
}
enum CodingKeys: String, CodingKey {
case type, difficulty, category, question, correct, incorrect
}
struct TriviaView: View {
@State private var trivia = [Trivia]()
var body: some View {
NavigationView {
List(trivia) { t in
VStack (alignment: .leading) {
Text(t.question)
.font(.headline)
.foregroundColor(.cyan)
Text(t.type)
.font(.body)
.foregroundColor(.black)
Text(t.difficulty)
.font(.body)
.foregroundColor(.black)
Text(t.correct)
.font(.headline)
.foregroundColor(.green)
}
}
.navigationTitle("Trivia Questions List")
.task {
await fetchTriviaData()
}
}
}
func fetchTriviaData() async {
// create the URL
guard let url = URL(string: "https://opentdb.com/api.php?amount=20&type=multiple)") else {
print("THIS URL DOES NOT WORK!")
return
}
// fetch the data
do {
let (results, _) = try await URLSession.shared.data(from: url)
// decode that data
if let decodedResponse = try? JSONDecoder().decode(TriviaResponse.self, from: results)
{
trivia = decodedResponse.results
}
} catch {
print("This data is not valid: \(error)")
// ecode the data
}
}
}
struct TriviaResponse: Decodable {
let results: [Trivia]
}
struct TriviaView_Previews: PreviewProvider {
static var previews: some View {
TriviaView()
}
}
这段代码的目标是能够使用URL查看json数据。当我单击假期列表的导航标题时,没有显示任何数据(在内容视图中)。我尝试过其他 API 链接,例如 JSON 的 API 占位符,并且它们有效。我无法弄清楚问题或差异。我也尝试过人工智能。我不知道我做错了什么,难道我必须使用API的所有数据变量吗?
我尝试使用这个问题作为我的新问题的模板这个API调用解析JSON数据有什么问题?,它不起作用,我想知道问题是什么。
伙计,尝试这个示例代码来修复您遇到的一些错误,但没有从上一篇文章中学到。
struct TriviaResponse: Decodable {
let results: [Trivia]
}
struct Trivia: Identifiable, Decodable {
let id = UUID()
var type: String
var difficulty: String
var category: String
var question: String
var correct: String?
// --- here, inside
enum CodingKeys: String, CodingKey {
case type, difficulty, category, question, correct
}
}
// for testing
struct ContentView: View {
var body: some View {
TriviaView()
}
}
struct TriviaView: View {
@State private var trivia = [Trivia]()
var body: some View {
NavigationStack { // <--- here
List(trivia) { t in
VStack (alignment: .leading) {
Text(t.question)
.font(.headline)
.foregroundColor(.cyan)
Text(t.type)
.font(.body)
.foregroundColor(.black)
Text(t.difficulty)
.font(.body)
.foregroundColor(.black)
Text(t.correct ?? "") // <--- here
.font(.headline)
.foregroundColor(.green)
}
}
.navigationTitle("Trivia Questions List")
.task {
await fetchTriviaData()
}
}
}
func fetchTriviaData() async {
// --- here had a extra `)`
guard let url = URL(string: "https://opentdb.com/api.php?amount=20&type=multiple") else {
print("THIS URL DOES NOT WORK!")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
// <--- here
let decodedResponse = try JSONDecoder().decode(TriviaResponse.self, from: data)
trivia = decodedResponse.results
} catch {
print("This data is not valid: \(error)")
}
}
}
1- 将
try?
更改为 try
do {
let (results, _) = try await URLSession.shared.data(from: url)
// decode that data
let decodedResponse = try JSONDecoder().decode(TriviaResponse.self, from: results)
trivia = decodedResponse.results
} catch {
print("This data is not valid: \(error)")
}
2-您会收到此错误
此数据无效: keyNotFound(CodingKeys(stringValue: " Correct", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "results", intValue: nil), _JSONKey(stringValue: "Index 0”,intValue:0)],debugDescription:“没有与键 CodingKeys 关联的值(stringValue:“正确”,intValue:nil)(“正确”)。”,underlyingError:nil))
这意味着没有正确的代号,但它应该是可选的正确答案