我遇到了這個問題,我不確定我做錯了什么,沒有顯示任何內容。我很肯定我做對了(好吧,我想我不是)但我無法弄清楚我做錯了什么。我是 Swift 的新手,所以我仍在學習,這就是為什么我要采用這種方法,因為我想以最簡單的方式做到這一點。所以我的問題是,我做錯了什么?
SwiftUI 代碼:
//
// ContentView.swift
// APIExample
import SwiftUI
struct Response: Codable {
var articles: [Article]
}
struct Article: Codable, Identifiable {
var id = UUID()
var author: String
var title: String
}
struct ContentView: View {
@State private var articles = [Article]()
func loadData() async {
guard let url = URL(string: "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=APIKEY") else {
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
articles = decodedResponse.articles
}
} catch {
print("Invalid data")
}
}
var body: some View {
List(articles, id: \.id) { item in
VStack(alignment: .leading) {
Text(item.author)
.font(.headline)
Text(item.title)
}
}.task {
await loadData()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
JSON:https : //pastebin.com/Zn4kY2BV
uj5u.com熱心網友回復:
你得到的錯誤是:
Invalid data: keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "articles", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))
您可以通過提供自定義解碼初始化來修復錯誤
struct Article: Codable, Identifiable {
var id = UUID()
var author: String
var title: String
enum CodingKeys: CodingKey {
case author
case title
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
author = try container.decode(String.self, forKey: .author)
title = try container.decode(String.self, forKey: .title)
}
}
uj5u.com熱心網友回復:
id在JSON 中,但不是您在代碼中指定它的方式:
struct Response: Codable {
var articles: [Article]
}
struct Source: Codable {
var id: String
var name: String
}
struct Article: Codable, Identifiable {
var source = Source
var author: String
var title: String
}
而對于你 ListView()
List(articles) { item in
VStack(alignment: .leading) {
Text(item.author)
.font(.headline)
Text(item.title)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/390819.html
