SwiftUI调用名言API无法显示数据:解码与列表ID问题排查
SwiftUI调用名言API显示数据的修复方案
1. 调整数据模型
放弃原来带results字段的Response结构,直接定义匹配API返回的Quote结构体:
struct Quote: Codable { let text: String let author: String? // API部分名言的author字段可能为null,所以用可选类型 }
2. 修正网络请求的解码逻辑
原来的代码试图解码带results的对象,现在要直接解码成[Quote]数组:
func fetchQuotes() async throws -> [Quote] { guard let url = URL(string: "https://type.fit/api/quotes") else { throw URLError(.badURL) } let (data, _) = try await URLSession.shared.data(from: url) // 直接解码为Quote数组,而非嵌套的Response结构 return try JSONDecoder().decode([Quote].self, from: data) }
3. 实现单条名言的UI显示
使用@State变量存储要展示的单条名言,在视图加载时请求数据并取数组中的第一条(或随机选一条):
struct ContentView: View { @State private var currentQuote: Quote? var body: some View { VStack(alignment: .leading, spacing: 16) { if let quote = currentQuote { Text(quote.text) .font(.title2) .italic() Text("- \(quote.author ?? "Anonymous")") .font(.subheadline) .foregroundColor(.gray) .frame(maxWidth: .infinity, alignment: .trailing) } else { ProgressView("Loading quote...") } } .padding() .task { do { let allQuotes = try await fetchQuotes() // 取第一条名言展示,也可以用Int.random(in: 0..<allQuotes.count)随机选 currentQuote = allQuotes.first } catch { print("请求失败:\(error.localizedDescription)") } } } }
问题原因回顾
之前运行无数据是因为解码逻辑不匹配API返回格式:API直接返回名言数组,而你的代码试图解析包含results字段的对象,导致解码失败后数据为空,自然无法显示内容。
内容的提问来源于stack exchange,提问作者brando
相关产品推荐
相关产品推荐

